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,348 @@
1
+ // src/core/http.ts
2
+ import { signedQuery } from './sign.js';
3
+ import { classify } from './errors.js';
4
+ import { normalize } from './envelope.js';
5
+ import { TokenBucket, limitFor } from './ratelimit.js';
6
+ import { redact } from './credentials.js';
7
+ const BASE = 'https://qiyukf.com';
8
+ /**
9
+ * 令牌桶按**路径**缓存,不按 id。
10
+ *
11
+ * ⚠️ 实测限频粒度是按路径的(设计稿 §7.4,183 次探测:同一路径 30 秒内连续调用
12
+ * 必返回 14009,跨不同路径的连续调用全部成功)。设计稿 §5.1 实测**线上**有 6 组 24 个
13
+ * 重复路径(当前骨架里没有,生成脚本补齐后会出现)——
14
+ * 按 id 分桶会让同一路径上的多个 id 各拿一份配额 —— 本地放行数倍流量,
15
+ * 服务端照旧按路径拒绝,Agent 看到的错误反而更难解释。
16
+ */
17
+ const buckets = new Map();
18
+ function bucketKey(spec) {
19
+ return spec.path ?? spec.id;
20
+ }
21
+ /**
22
+ * 取该接口的限频行。
23
+ *
24
+ * ⚠️ **桶按 path 缓存,限频行按 id 查** —— 这两者必须靠一条注册表不变量兜住:
25
+ * **同一条路径上的所有 id,限频行必须一致**。
26
+ *
27
+ * 若不一致,桶的窗口就取决于该路径上**谁先被调用**(那一行只在建桶时读一次),
28
+ * 结果顺序敏感。这里刻意不做"遍历所有同路径 id 取最严"——限频表里的 id
29
+ * 大多不在注册表里(注册表目前只有 11 条骨架),遍历不到它们,
30
+ * 那种"取最严"是假的安全感。真正管用的是把不变量测出来(见 registry 测试)。
31
+ */
32
+ function limitForSpec(spec) {
33
+ return limitFor(spec.id);
34
+ }
35
+ function bucketFor(spec) {
36
+ const key = bucketKey(spec);
37
+ let b = buckets.get(key);
38
+ if (!b) {
39
+ const limit = limitForSpec(spec);
40
+ b = new TokenBucket(limit?.limit ?? null, limit?.windowSeconds ?? null);
41
+ buckets.set(key, b);
42
+ }
43
+ return b;
44
+ }
45
+ /** 仅测试用:清空桶缓存,避免用例之间通过模块级状态互相污染。 */
46
+ export function __resetBuckets() {
47
+ buckets.clear();
48
+ }
49
+ /**
50
+ * 把 body 序列化成**将要原样发送**的字符串。
51
+ *
52
+ * ⚠️ 不传 body 与传 `{}` 是**两条不同的服务端代码路径**(实测会泄漏不同的 Java NPE 措辞),
53
+ * 因此这里必须保留 undefined 与 {} 的区别,不能用 falsy 判断合并。
54
+ * ⚠️ 不做 key 排序:排序会让 md5 与"实际发送的字节"脱钩,从而返回 14002。
55
+ */
56
+ export function buildBody(body) {
57
+ if (body === undefined)
58
+ return undefined;
59
+ return JSON.stringify(body);
60
+ }
61
+ /**
62
+ * 网络层错误。**必须脱敏** —— message 是否含 URL 因失败类型而异(连接失败恒为
63
+ * `"fetch failed"`,见本任务测试用例的注释(http.test.ts 的「redact 会擦掉异常
64
+ * message 里的 appKey…」);构造类异常带完整 URL),与其逐条判断
65
+ * 哪些异常路径会带 URL,不如**无条件** redact —— URL 的查询串就是
66
+ * `appKey=...&time=...&checksum=...`。
67
+ */
68
+ function networkError(e, creds) {
69
+ const raw = e instanceof Error ? e.message : String(e);
70
+ return {
71
+ code: 'network',
72
+ kind: 'network',
73
+ retryable: true,
74
+ message: redact(raw, creds),
75
+ hint: '网络层故障,可重试',
76
+ };
77
+ }
78
+ /**
79
+ * undici 在**请求构造阶段**抛出的错误(如给 GET 传 body)与
80
+ * 真正的网络失败都是 `TypeError`,但前者**没有 `cause`**、后者有
81
+ * (`cause` 是底层 socket 错误,形如 `ECONNREFUSED`)。
82
+ *
83
+ * ⚠️ G1 起 `call()` 已在入口拦下 GET + body(直接抛 usage),所以这条分支
84
+ * 不再靠它兜底;保留分类是因为**其他**构造类错误(将来新增的参数拼装缺陷)
85
+ * 仍是本地用法问题,不能报成网络故障。
86
+ *
87
+ * ⚠️ 必须把两者分开:构造错误是**本地用法问题**,重试一万次也一样,
88
+ * 而网络失败必须退避重试。此前 `catch` 一律走 `networkError` —— 实测
89
+ * `GET` + body 会被当成网络故障重试 3 次、返回退出码 3("网络错误"),
90
+ * Agent 会以为服务端有问题。判据用 `TypeError && !cause` 而不是"有无 cause",
91
+ * 是为了不误伤 `fetch` 被 mock 成抛普通 `Error` 的测试夹具(那些没有 cause
92
+ * 却代表真实网络故障)。
93
+ *
94
+ * ⚠️ **注释此前把"非法 URL"列为已覆盖用例,那是错的**(Node 24.19.0 实测):
95
+ * `fetch("http://[::bad")` 抛的 TypeError **带 `cause`**(`cause.code ===
96
+ * 'ERR_INVALID_URL'`),因此本函数对它返回 **false** → 落进 `networkError` →
97
+ * `kind:'network'`、退出码 3、**重试 3 次**,与本函数的分类意图相反。
98
+ * 之所以不修:判据若改成"看 `cause.code` 属不属于 URL 构造类",就把正确性
99
+ * 绑在 undici 的内部错误码上(稳定性差),而实测生产路径上也构造不出
100
+ * 非法 URL —— `loadSpecs` 校验 `path` 必须以 `/` 开头,URL 由
101
+ * `${BASE}${spec.path}?${q}` 拼成。**这是注释与代码的已知矛盾,不是运行时缺陷**;
102
+ * 若将来真的需要覆盖非法 URL,应显式加判据并加测试,而不是靠改注释掩盖。
103
+ */
104
+ function isLocalRequestError(e) {
105
+ return e instanceof TypeError && !e.cause;
106
+ }
107
+ /** 发起一次已签名调用。业务错误以分类后的异常抛出。 */
108
+ export async function call(spec, body, opts) {
109
+ const now = opts.now ?? (() => Date.now());
110
+ const creds = opts.credentials;
111
+ // ⚠️ GET 请求**绝不带 body**(G1 交付)。此前 `call()` 对任何 method 都发
112
+ // `body: bodyStr`,GET + body 会被 undici 在构造阶段拒掉 —— 分类上兜住了
113
+ // (见 `isLocalRequestError`),但那是一条**错误驱动的**路径:先构造一个非法
114
+ // 请求、再靠异常猜原因。现在在入口就把两件事分开:
115
+ // · GET + 调用方给了 body → 本地用法错误(静默丢弃会让 Agent 以为 body 生效了);
116
+ // · GET 不带 body → 正常发送,签名用 `md5('')`(`bodyStr ?? ''`,与"不传 body
117
+ // 的 POST"同一签名口径;这是 2026-10-02 真实凭证实测的约定)。
118
+ // ⚠️ 当前 154 条注册表里唯一的 GET(`get_token`)是 inbound、不可主动调用,
119
+ // 所以本分支目前只由合成 spec 的测试覆盖 —— 不要把它读成"线上 GET 已实测"。
120
+ if (spec.method === 'GET' && body !== undefined) {
121
+ throw Object.assign(new Error(`接口 ${spec.id} 是 GET 接口,不接受请求体`), { code: 'usage', kind: 'usage', retryable: false,
122
+ // ⚠️ 不要写「参数走 query 串」—— 本 CLI 没有 GET 的 query 参数通道(评审发现)。
123
+ // 写到不存在的通道上,调用方会去找一个没有的 flag。如实说明现状。
124
+ hint: '本 CLI 目前没有 GET 的 query 参数通道;若该接口需要参数,请去掉 body 后重试' +
125
+ '(当前注册表里的 GET 接口都不可主动调用,普通调用走不到这里)' });
126
+ }
127
+ // ⚠️ 经上面的守卫,走到这里时 GET 必然无 body —— `buildBody(undefined)`
128
+ // 返回 undefined,fetch 收到的就是 `body: undefined`,签名口径 `md5('')`。
129
+ // 不再写 `GET ? undefined : buildBody(body)`:有守卫在,那是恒等分支。
130
+ const bodyStr = buildBody(body);
131
+ if (!opts.noRetry && !bucketFor(spec).tryAcquire(now())) {
132
+ const waitMs = bucketFor(spec).nextAvailableAt(now());
133
+ throw Object.assign(new Error(`接口 ${spec.id} 触发本地限频,还需等待约 ${Math.ceil(waitMs / 1000)} 秒`), { code: 'local_rate_limit', kind: 'rate_limit', retryable: true,
134
+ // 本地令牌桶算出的精确等待(不是猜的)—— source: 'local'
135
+ retryAfter: { seconds: Math.ceil(waitMs / 1000), source: 'local' } });
136
+ }
137
+ let signedTime = Math.floor(now() / 1000);
138
+ // 两个独立的预算:网络重试与 14003 重签重试互不挤占。
139
+ // 共用一个计数器会让"先网络失败一次"把重签重试的机会吃掉。
140
+ let networkAttempts = 0;
141
+ let resigned = false;
142
+ for (;;) {
143
+ // ⚠️ 不传 body 时用 `md5('')` 签名 —— 即 `bodyStr ?? ''`。这是**实测确认**的
144
+ // (2026-10-02,真实凭证):对 `ticket.search` 不传 body 得到 `code:200`,
145
+ // 若服务端对空 body 另有约定(如跳过 md5),这里会返回 `14002 Bad checksum`。
146
+ // 与传 `{}`(`md5('{}')`)是两条不同路径,两者都实测为 `code:200`。
147
+ const q = signedQuery(creds.appKey, creds.appSecret, bodyStr ?? '', signedTime);
148
+ const url = `${BASE}${spec.path}?${q}`;
149
+ let res;
150
+ try {
151
+ res = await fetch(url, {
152
+ method: spec.method,
153
+ // 显式设置:undici 默认 text/plain,服务端会按非 JSON 解析
154
+ headers: { 'Content-Type': 'application/json', 'Accept-Encoding': 'identity' },
155
+ body: bodyStr,
156
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),
157
+ });
158
+ }
159
+ catch (e) {
160
+ // ⚠️ 先分辨"本地构造错误"(如给 GET 传 body)—— 那不是网络故障,
161
+ // 重试无用,且把它报成 network/退出码 3 会让 Agent 误以为是服务端问题。
162
+ // (⚠️ 判据只覆盖"无 cause 的 TypeError";非法 URL 带 cause,不在此列 —— 见
163
+ // `isLocalRequestError` 的文档注释,那是已知的注释/行为矛盾,生产路径不可达。)
164
+ if (isLocalRequestError(e)) {
165
+ throw Object.assign(new Error(`请求构造失败:${redact(e instanceof Error ? e.message : String(e), creds)}`), { code: 'usage', kind: 'usage', retryable: false,
166
+ hint: '这是 CLI 侧的请求构造问题(如给 GET 传了 body),重试无用' });
167
+ }
168
+ const err = networkError(e, creds);
169
+ // ⚠️ **危险接口(写/破坏性)绝不自动重发。**
170
+ //
171
+ // 网络错误有两种,从 `fetch` 抛出的异常上**无法区分**:
172
+ // · 请求根本没发出去(DNS 失败、连接被拒)—— 重发是安全的
173
+ // · 请求已到达且**已被服务端执行**,断在响应阶段
174
+ // (实测形态:`SSL: UNEXPECTED_EOF_WHILE_READING`)—— 重发会**再执行一次**
175
+ // 对 `message.send` / `deleteKnowledges` 这类接口,后者意味着
176
+ // **一次 `--yes` 确认发出多条相同的写请求**(实测:一次调用实际发出 2–3 次)。
177
+ // 门禁的语义是"人确认了**一次**这个操作",自动重发把它变成了 N 次,
178
+ // 而 Agent 无从知道服务端到底执行了几次 —— 这正是 `risk: 'irreversible'`
179
+ // 承诺要避免的事。
180
+ //
181
+ // 读接口没有这个问题(重发最多多读一次),所以只在 `spec.dangerous` 上收窄。
182
+ // 判定放在**抛出之前**:给 Agent 一个可重试的 network 错误,
183
+ // 由它自己决定要不要再确认一次 —— 而不是 CLI 替它做这个决定。
184
+ if (spec.dangerous) {
185
+ throw Object.assign(new Error(err.message), err, {
186
+ hint: '危险接口的网络故障**不会被自动重试** —— 请求可能已被服务端执行,' +
187
+ '重发会再执行一次。请先用只读接口确认当前状态,再决定是否重新调用',
188
+ });
189
+ }
190
+ if (opts.noRetry || networkAttempts >= 2)
191
+ throw Object.assign(new Error(err.message), err);
192
+ await sleep(300 * 2 ** networkAttempts);
193
+ networkAttempts++;
194
+ continue;
195
+ }
196
+ let raw;
197
+ try {
198
+ raw = await res.json();
199
+ }
200
+ catch (e) {
201
+ // ⚠️ 走到这里的原因有**两大类**,判据不能只看 HTTP 状态码:
202
+ //
203
+ // 【甲】响应体读取本身失败(不是"body 不是 JSON")—— `res.json()` 抛
204
+ // `TimeoutError` / `AbortError` / `TypeError`(undici 的 body 流错误)。
205
+ // 实测(Node 24,本地服务器发一半 body 后挂住 + `timeoutMs` 250ms):
206
+ // `res.status` 此时**已经是 200**,而 `await res.json()` 抛 `TimeoutError`。
207
+ // 这类是**瞬时网络故障**,必须 `network`/可重试 —— 否则 Agent 会直接放弃
208
+ // 一个本该退避重试的调用。⚠️ `AbortSignal.timeout` 对"建立连接"与"读取 body"
209
+ // 是**同一个** signal,"接收大结果集时读慢/断流"是常见瞬时故障。
210
+ // 【乙】body 完整到达但不是合法 JSON —— `res.json()` 抛 `SyntaxError`。
211
+ // 这一类才轮到"看状态码":404/429/5xx 各有含义,其余是服务端畸形响应。
212
+ //
213
+ // 区分依据是**异常类型**,不是响应体内容:`SyntaxError` → 乙;其余 → 甲。
214
+ const isReadFailure = !(e instanceof SyntaxError);
215
+ if (isReadFailure) {
216
+ const err = networkError(e, creds);
217
+ // 与 fetch 抛错那条分支保持同一套语义:危险接口不自动重发,
218
+ // 读接口退避重试(预算与 fetch 失败共用 `networkAttempts`)。
219
+ if (spec.dangerous) {
220
+ throw Object.assign(new Error(err.message), err, {
221
+ hint: '危险接口的网络故障**不会被自动重试** —— 请求可能已被服务端执行,' +
222
+ '重发会再执行一次。请先用只读接口确认当前状态,再决定是否重新调用',
223
+ });
224
+ }
225
+ if (opts.noRetry || networkAttempts >= 2)
226
+ throw Object.assign(new Error(err.message), err);
227
+ await sleep(300 * 2 ** networkAttempts);
228
+ networkAttempts++;
229
+ continue;
230
+ }
231
+ //
232
+ // 1. 404 —— 路由不存在。设计稿 §4.3 实测**两种 404 形态**:
233
+ // `/openapi/*` 返回 Spring JSON(那个在 envelope.ts 里处理,不会走到这),
234
+ // 而 `/platform/api/*` 返回 **nginx HTML** —— 它必然走到这里。
235
+ // 这是**注册表 bug**(路径写错了),不是服务端故障。判成 internal 会让
236
+ // Agent 以为"服务端有缺陷",而正确动作是报给我们改注册表。
237
+ // 2. 网关/代理故障(429 / 500 / 502 / 503 / 504)—— 瞬时,Agent 必须退避重试;
238
+ // 判成 retryable:false 会让它直接放弃。
239
+ // ⚠️ 必须与 `errors.ts` 的 `case '429','500','502','503','504'` 用**同一集合** ——
240
+ // 否则同一个 500 会因代理返回 HTML 还是 Spring JSON 而被判成 internal 或 network,
241
+ // 取决于代理行为,不是调用方能解释的差异。
242
+ // 3. 服务端真的返回了非 JSON 的畸形响应 —— 那是内部缺陷,重试无用。
243
+ //
244
+ // 区分(乙类内部的)依据是 HTTP 状态码,不是响应体内容。
245
+ const status = res.status;
246
+ if (status === 404) {
247
+ throw Object.assign(new Error(`路由不存在(HTTP 404,返回的不是 JSON)—— 注册表里的路径可能有误`), { code: '404', kind: 'route_not_found', retryable: false,
248
+ hint: '该接口在服务端不存在。这通常是注册表的路径写错了,请报告此问题;重试无用' });
249
+ }
250
+ // ⚠️ 401/403 与 errors.ts 一致归为 auth(网关 HTML 拒绝页也走这里)
251
+ if (status === 401 || status === 403) {
252
+ throw Object.assign(new Error(`请求被拒绝(HTTP ${status},返回的不是 JSON)`), { code: String(status), kind: 'auth', retryable: false,
253
+ hint: `请求被拒绝(HTTP ${status})—— 凭证或权限问题,重试无用` });
254
+ }
255
+ const transient = status === 429 || status === 500 || status === 502 ||
256
+ status === 503 || status === 504;
257
+ throw Object.assign(new Error(`响应不是合法 JSON(HTTP ${status})` +
258
+ (transient ? '。这通常是网关/代理的瞬时故障,可退避重试' : '')),
259
+ // 瞬时故障归为 `network`(退出码 3),与 fetch 抛错同一类 ——
260
+ // 两者都是"请求没到达业务层",而不是"业务层拒绝了请求"。
261
+ transient
262
+ ? { code: String(status), kind: 'network', retryable: true,
263
+ hint: '网关瞬时故障(HTTP 429/5xx),请退避后重试' }
264
+ : { code: String(status), kind: 'internal', retryable: false });
265
+ }
266
+ const norm = normalize(raw, spec.envelope ?? undefined);
267
+ // 时间戳超期:core 层用新时间戳重签重试一次,对 Agent 永不可见。
268
+ // ⚠️ 必须一并检查 `opts.noRetry` —— 否则 `noRetry:true` 下仍会发出第二个
269
+ // 请求,与 `CallOptions.noRetry` 的注释("跳过令牌桶与重试")不符。
270
+ // 网络重试那一支已有这个检查,这里漏了会让两条重试路径的语义不一致。
271
+ //
272
+ // ⚠️ **这里对危险接口是安全的,不要加上 `spec.dangerous` 判断** —— 与上面的
273
+ // 网络重试分支不同。`14003` 是服务端在**执行任何逻辑之前**对鉴权时间戳的拒绝,
274
+ // 请求体根本没有被处理;用新时间戳重发一次,服务端只会执行**一次**。
275
+ // 网络故障那一支才是危险的(请求可能已被执行、断在响应阶段)。
276
+ // 两条重试路径的危险性相反,判据必须分开 —— 把它们一起"加固"会让
277
+ // 本机时钟偏移时所有写接口直接失败,而那正是 14003 重签要解决的唯一问题。
278
+ if (norm.code === '14003' && !resigned && !opts.noRetry) {
279
+ // ⚠️ **必须保证严格递增,不能只是重新取一次时钟。**
280
+ // 两次 `Math.floor(now() / 1000)` 之间只隔一次 fetch 往返(通常 < 100ms),
281
+ // 落在同一秒内的概率极高 —— 此时 `time` 不变、md5(body) 不变,
282
+ // 于是 `checksum` 也逐字节相同,**重试等于把刚被拒的请求原样重发**。
283
+ // 设计稿 §4.3 承诺「core 层自动重新签名并重试,对 Agent 永不可见」(逐字引文;
284
+ // "永"的前提 —— 时钟偏移非永久 —— 见复核重点第 4 条的讨论),
285
+ // 若第二次与第一次签名相同,这条承诺实际不成立(本机时钟正常时也一样)。
286
+ // `+ 1` 是最小改动:即使本机时钟完全静止,也保证新签名的 time 不同。
287
+ // 若本机时钟真的偏了 >5 分钟,这次重试仍会被拒,随后落到 `bad_time`
288
+ // (`retryable: false` + 校对时钟的 hint)—— 那正是应有的终态。
289
+ signedTime = Math.max(Math.floor(now() / 1000), signedTime + 1);
290
+ resigned = true;
291
+ continue;
292
+ }
293
+ if (!norm.ok) {
294
+ const err = classify(norm.code, norm.messageText);
295
+ // 冷却秒数由**限频表**决定,不由分派器猜 —— 实测冷却随接口变化
296
+ const limit = limitForSpec(spec);
297
+ if (err.kind === 'rate_limit') {
298
+ // ⚠️ **必须标出这个数字的来源**(2026-10-05 修)。
299
+ // 此前是裸的 `{ seconds: N }`,Agent 分不出来:设计稿 §11.2 D 的分流协议
300
+ // 按 `retry_after > 60` 二分(`> 60` → 不要 sleep,去查本地库),而**兜底值
301
+ // 恰好就是 60**、实测值里也真的有 60(ipcc 报表)—— 同一个数字承载不同的
302
+ // 来源与可信度,Agent 无从判断该不该信。
303
+ // ⚠️ 直接用**限频表自己的 `source`**,不要压成一个布尔:表里 6 行是
304
+ // `'doc'`(文档值、从未实测),压成 `measured: true` 会把它们谎报成实测。
305
+ err.retryAfter = limit
306
+ ? { seconds: limit.windowSeconds, source: limit.source }
307
+ // 接口没登记限频、但服务端确实报了限流 —— 此时**必须**给个保守兜底,
308
+ // 否则 Agent 收到限流却拿不到任何等待建议,只能立刻重试、继续吃 14009。
309
+ //
310
+ // ⚠️ **兜底值恰好等于设计稿 §11.2 D 的分流阈值(`retry_after > 60`),这是刻意的。**
311
+ // 该协议说:`> 60` → 「**不要 sleep**;改为查询本地数据库」。
312
+ // 本计划**没有 `store/`**(见「已知缺口」),所以"查询本地数据库"这条动作
313
+ // 对本计划的 Agent **不可执行** —— 那等于把 Agent 指向一个不存在的能力。
314
+ // 落在 `<= 60` 这一侧(可以 sleep)才是当前唯一可执行的下一步。
315
+ // → **不要**为了让"未登记接口也走不要 sleep 分支"而把这个值改成 61:
316
+ // 那会把 Agent 送去查一个本计划没有的数据库。等有 `store/` 之后再改,
317
+ // 届时这个兜底值才有第二种正确取法。
318
+ : { seconds: 60, source: 'fallback' };
319
+ // ⚠️ 兜底时**必须**说清它不是实测值,并指明真正的配额要去哪查 ——
320
+ // 否则 Agent 睡满 60 秒就重试,很可能再吃一次 14009。
321
+ if (!limit) {
322
+ err.hint = '该接口未登记在本地限频表,下面的等待秒数是**保守兜底值、不是实测冷却**,' +
323
+ '可能短于服务端真实冷却(睡完仍可能再吃限频)。真实配额见接口文档。' +
324
+ (err.hint ? ` 原分类提示:${err.hint}` : '');
325
+ }
326
+ else if (limit.source === 'doc') {
327
+ // ⚠️ `doc` 来源也必须说清(2026-10-07 补)。限频表里 6 行是 `source: 'doc'`
328
+ // —— 秒数抄自厂商文档、**从未实测过**。此前它与 `observed` 走同一段代码、
329
+ // hint 一字不差,等于把文档值当实测值报给 Agent —— 与 `source` 存在的
330
+ // 唯一目的(让 Agent 分辨该不该信)相反。
331
+ // `source` 字段本身对 Agent 零解释(见「已知缺口」登记),所以 hint 是
332
+ // 唯一能传达这件事的渠道 —— 与 `fallback` 那条同一条理由。
333
+ err.hint = '下面的等待秒数取自**厂商文档、未对本租户实测**,' +
334
+ '真实冷却可能不同(睡完仍可能再吃限频)。' +
335
+ (err.hint ? ` 原分类提示:${err.hint}` : '');
336
+ }
337
+ }
338
+ // ⚠️ message 必须放在**最后** —— Object.assign 是右覆盖左,
339
+ // 若写成 Object.assign(new Error(redact(...)), err),err.message 会把
340
+ // 脱敏结果原样冲掉,脱敏形同虚设。
341
+ throw Object.assign(new Error(), err, { message: redact(err.message, creds) });
342
+ }
343
+ return norm;
344
+ }
345
+ }
346
+ function sleep(ms) {
347
+ return new Promise((r) => setTimeout(r, ms));
348
+ }
@@ -0,0 +1,126 @@
1
+ // src/core/ratelimit.ts
2
+ /**
3
+ * 逐接口限频表。**不要外推** —— 实测分布极不统一:
4
+ * ⚠️ 冷却取值**不是**设计稿早前说的"30s/60s/10s/5min 四种"——那张表的 5 分钟
5
+ * 已被实测推翻为 20 秒。本表实际用到 **6 档:1 / 10 / 20 / 30 / 60 / 180 秒**
6
+ * (180 秒是 `robot.data.knowledge`,注释里写作"长达数分钟")。
7
+ * 错误码也**不止三种**:本表覆盖 14009 / 12001 / 8011,另有 `icoutcall.history.*`
8
+ * 走 **14402**、知识库取数走 **14500**("太频繁"这一语义横跨多个码,见 errors.ts 的
9
+ * 按文本分派)。还有些接口**完全没有限频**(本表里为 null)。
10
+ * → 任何"统一冷却时间""只认 14009"的假定都是错的。
11
+ * 未登记的接口返回 null(不限频)。
12
+ */
13
+ export const RATE_LIMITS = {
14
+ // 10 个报表接口:约 30 秒冷却,按路径各自独立
15
+ 'statistic.overview': { limit: 1, windowSeconds: 30, source: 'observed', scope: 'endpoint' },
16
+ 'statistic.staffworklod': { limit: 1, windowSeconds: 30, source: 'observed', scope: 'endpoint' },
17
+ 'statistic.staffquality': { limit: 1, windowSeconds: 30, source: 'observed', scope: 'endpoint' },
18
+ 'statistic.staffAttendance': { limit: 1, windowSeconds: 30, source: 'observed', scope: 'endpoint' },
19
+ 'statistic.satisfaction.report': { limit: 1, windowSeconds: 30, source: 'observed', scope: 'endpoint' },
20
+ 'statistic.performance': { limit: 1, windowSeconds: 30, source: 'observed', scope: 'endpoint' },
21
+ 'statistic.salaryDetail': { limit: 1, windowSeconds: 30, source: 'observed', scope: 'endpoint' },
22
+ 'robot.statistic.summary': { limit: 1, windowSeconds: 30, source: 'observed', scope: 'endpoint' },
23
+ 'ai.statistic.transferHuman': { limit: 1, windowSeconds: 30, source: 'observed', scope: 'endpoint' },
24
+ 'data.overview.session': { limit: 1, windowSeconds: 30, source: 'observed', scope: 'endpoint' },
25
+ // 呼叫坐席/团队历史:实测约 20 秒冷却,超限返回 14402(设计稿 §4.3)
26
+ 'icoutcall.history.seat': { limit: 1, windowSeconds: 20, source: 'observed', scope: 'endpoint' },
27
+ 'icoutcall.history.team': { limit: 1, windowSeconds: 20, source: 'observed', scope: 'endpoint' },
28
+ // 报表域:ipcc 是 10 次/60 秒滚动窗口(与其余报表的 30 秒不同)
29
+ 'data.overview.ipcc': { limit: 10, windowSeconds: 60, source: 'observed', scope: 'endpoint' },
30
+ // 知识库取数接口实测也是 14009,且冷却长达数分钟(不是 30 秒)
31
+ 'robot.data.knowledge': { limit: 1, windowSeconds: 180, source: 'observed', scope: 'endpoint' },
32
+ // 会话导出:创建每 10 秒 6 次;检查无限频
33
+ 'export.session': { limit: 6, windowSeconds: 10, source: 'observed', scope: 'endpoint' },
34
+ 'export.session.check': null,
35
+ // 咨询分类:实测 60 秒
36
+ 'online.session.category.list': { limit: 1, windowSeconds: 60, source: 'observed', scope: 'endpoint' },
37
+ // 知识库:大部分 1/s,详情与规则回答 10/s
38
+ 'ai.knowledge.getCategoryTree': { limit: 1, windowSeconds: 1, source: 'observed', scope: 'endpoint' },
39
+ 'ai.knowledge.search': { limit: 1, windowSeconds: 1, source: 'observed', scope: 'endpoint' },
40
+ 'ai.knowledge.getDetail': { limit: 10, windowSeconds: 1, source: 'doc', scope: 'endpoint' },
41
+ // 知识库写接口:限流取自官方字段表(设计稿 §5.4.1),非实测 —— 这 5 个接口
42
+ // 从未被调用过。⚠️ 三个 1/s 的接口(addKnowledge / editKnowledge / deleteKnowledges)
43
+ // 会让批量编辑被限流。
44
+ //
45
+ // ⚠️ **本计划的 `call()` 不会"串行化"批量编辑 —— 不要以为登记了限频就安全了。**
46
+ // 令牌桶是**进程内**的 `Map`(见 http.ts 的 `buckets`),没有持久化;而 `api call`
47
+ // 是**一次性进程**(一次调用后退出)。所以跨 `qiyu api call` 的调用之间**没有任何
48
+ // 共享状态**:每次都是全新的空桶,限频表对它们完全不起作用。
49
+ // 实测:进程内连续调 4 次 1/s 的接口 → 第 1 次发出、后 3 次立刻抛 `rate_limit`
50
+ // (等 1s)—— 它**不会替你等**,只是把"要等"这件事报给调用方。
51
+ // → 限频表真正约束的是**将来那个批量命令**(单进程内循环调用,如计划 2 的知识库
52
+ // 批量编辑);对当前的单次 `api call`,它只在"同一个进程内被调用多次"时才生效。
53
+ // 单次 `api call` 撞 14500 时,`call()` 给出的保守 `retryAfter` 才是 Agent 的唯一依据。
54
+ 'ai.knowledge.addKnowledge': { limit: 1, windowSeconds: 1, source: 'doc', scope: 'endpoint' },
55
+ 'ai.knowledge.editKnowledge': { limit: 1, windowSeconds: 1, source: 'doc', scope: 'endpoint' },
56
+ 'ai.knowledge.deleteKnowledges': { limit: 1, windowSeconds: 1, source: 'doc', scope: 'endpoint' },
57
+ 'ai.knowledge.editChannelAnswer': { limit: 10, windowSeconds: 1, source: 'doc', scope: 'endpoint' },
58
+ 'ai.knowledge.editKnowledgeNoSimilars': { limit: 10, windowSeconds: 1, source: 'doc', scope: 'endpoint' },
59
+ 'robot.data.getQuestionsByCategoryName': { limit: 1, windowSeconds: 1, source: 'observed', scope: 'endpoint' },
60
+ 'robot.data.queryStandardByEffectiveQuestion': { limit: 1, windowSeconds: 1, source: 'observed', scope: 'endpoint' },
61
+ 'robot.data.queryStandardQuestionList': { limit: 1, windowSeconds: 1, source: 'observed', scope: 'endpoint' },
62
+ // 如实测:没有任何限频(设计稿 §7.4 明确列出这 5 个)
63
+ // ⚠️ 显式写 null 而不是省略 —— 省略会退化成"未登记"的默认值,而这两者
64
+ // 在审计上不同:null 表示"实测过,确实没有",省略表示"没测过"。
65
+ 'chat.queue.group.query': null,
66
+ 'evaluation.setting.get': null,
67
+ 'event.queryQueueStatus': null,
68
+ 'smstask.status': null,
69
+ 'online.session.customfield.template': null,
70
+ };
71
+ export function limitFor(endpointId) {
72
+ // 必须用 hasOwn —— 否则 'constructor' / 'toString' 会命中原型链上的函数,
73
+ // 返回一个没有 limit 字段的东西,后续取属性得到 undefined 而不是 null。
74
+ return Object.hasOwn(RATE_LIMITS, endpointId) ? RATE_LIMITS[endpointId] : null;
75
+ }
76
+ /**
77
+ * **三态**查询(`api schema` 的消费方):未登记 → `undefined`;
78
+ * 登记且实测无限制(显式 null)→ `null`;有限频 → `RateLimit`。
79
+ *
80
+ * ⚠️ 不要用它替换 `limitFor`:`call()` 的语义是"未登记与显式 null 都视为不限频",
81
+ * 两者合并成 `null` 才是它要的。三态只用于**如实告诉 Agent 这个值是怎么来的** ——
82
+ * 「没测过」与「测过、确实没有」在审计上是两件事,不能压成一个。
83
+ */
84
+ export function registeredRateLimit(endpointId) {
85
+ return Object.hasOwn(RATE_LIMITS, endpointId) ? RATE_LIMITS[endpointId] : undefined;
86
+ }
87
+ /**
88
+ * 滑动窗口令牌桶。limit 或 windowSeconds 为 null/0 时永不拒绝。
89
+ *
90
+ * ⚠️ 构造参数是**秒**,与 `RateLimit.windowSeconds` 同单位 —— 内部换算成毫秒。
91
+ * 调用方若要传毫秒,必须显式乘 1000,不要依赖构造器猜。
92
+ * now 由调用方注入,便于测试。
93
+ */
94
+ export class TokenBucket {
95
+ limit;
96
+ clock;
97
+ stamps = [];
98
+ windowMs;
99
+ constructor(limit, windowSeconds, clock = () => Date.now()) {
100
+ this.limit = limit;
101
+ this.clock = clock;
102
+ this.windowMs = windowSeconds === null ? null : windowSeconds * 1000;
103
+ }
104
+ enabled() {
105
+ return !!this.limit && !!this.windowMs && this.limit > 0 && this.windowMs > 0;
106
+ }
107
+ tryAcquire(now = this.clock()) {
108
+ if (!this.enabled())
109
+ return true;
110
+ this.stamps = this.stamps.filter((t) => now - t < this.windowMs);
111
+ if (this.stamps.length >= this.limit)
112
+ return false;
113
+ this.stamps.push(now);
114
+ return true;
115
+ }
116
+ /** 还需要等待多少毫秒才能再次获得配额;可以立刻调用时返回 0。 */
117
+ nextAvailableAt(now = this.clock()) {
118
+ if (!this.enabled())
119
+ return 0;
120
+ const live = this.stamps.filter((t) => now - t < this.windowMs);
121
+ if (live.length < this.limit)
122
+ return 0;
123
+ const oldest = Math.min(...live);
124
+ return oldest + this.windowMs - now;
125
+ }
126
+ }