dsh-connect-madao 0.9.0 → 0.9.2

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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,70 @@
1
+ # 更新日志
2
+
3
+ 本项目遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
4
+
5
+ ## 0.9.2 — 2026-11-20
6
+
7
+ 本版主要来自社区贡献者 **[@vzhentian1-design](https://github.com/vzhentian1-design)** 的
8
+ [PR #1](https://github.com/XLNC-L/dsh-connect-madao/pull/1)。该 PR 基于 11-16 的 main,
9
+ 之后 `server.ts` / `sse.ts` / `lib/index.js` 均已大改,无法直接合并;这里按「只移植协议
10
+ 增量」的方式重放了他的四项改动,其余部分(含提交进仓库的 `lib/index.js` 构建产物)
11
+ 未采用,产物由本仓库重新构建生成。原始思路与判据均来自他。
12
+
13
+ ### 新增
14
+
15
+ - **`POST /v1/ops/confirm`** —— 补上漏掉的协议环节。
16
+ 上游是四态状态机 `ELIGIBLE → CLAIMED → CONFIRMED → CONSUMED`:`claim` 之后积分
17
+ 虽然已经到账,状态却停在 `CLAIMED`("已领取"),必须再 `confirm` 一次才变
18
+ `CONFIRMED`("已到账")。本仓库之前只做了 `claim`,所以网页端会一直显示「已领取」。
19
+ - `confirm` 的 body **只认 `{campaignId}`**,多带 `channel` 会 `HTTP 400 HDN.1000
20
+ channel : unknown exception`(实测)。
21
+ - `confirm` **不校验状态机**:对已经 `CONFIRMED` 的活动再调用也返回 `code=0`。
22
+ 因此只对 `status === "CLAIMED"` 的活动调用,绝不随手乱发。
23
+ - 列表里遇到 `CLAIMED` 时只补 `confirm`,不重复 `claim`。
24
+ - **多活动扫描 + `type` / `triggerEvent` 白名单** —— 之前只认死 `campaignId=34`,
25
+ 其它签到类活动全部漏领(实测曾见过 `campaignId=40`「Skill创新赛每日签到礼」
26
+ 每天 1000 分,是每日签到的十倍)。现在:
27
+ - 判据按可靠程度:`type === 'USER_LOGIN'` → `extra.triggerEvent === 'user.login'`
28
+ → 标题含「签到」且不含「报名 / 认证 / 注册 / 邀请」(前两者缺失时才用标题兜底)。
29
+ - 只领 `triggerMode !== 'AUTO_GRANT'` 且 `claimable === true` 且
30
+ `status === 'ELIGIBLE'` 的活动。
31
+ - **不替用户报名/认证**:报名、学生认证、邀请有礼这类一次性动作一律跳过,
32
+ 宁可漏领也不误签。
33
+ - 新增 `POST /diag/checkin/all`(面板上的「领全部」按钮)。
34
+ - **积分到期预警** —— 上游在额度接口里给了 `package_credit_expiring_amount`
35
+ (即将到期的数量)和顶层的 `start_date` / `end_date`,之前一个字段都没读,
36
+ 用户只能等某天突然发现余额少了一大截。现在读取并算出三档提醒
37
+ (`urgent` ≤ 2 天 / `warn` ≤ 7 天 / `info`),通过 `/diag/account` 的
38
+ `creditExpiry` 字段暴露,面板上额度行下面直接显示。
39
+ - 实测这两个汇总指标报的是**同一个值**(同一批积分),取首个命中即可,
40
+ 累加会把 33.54 说成 67.08。
41
+ - **`LICENSE`** —— MIT 全文。之前仓库根确实没有;`package.json` 的 `files`
42
+ 也一并补上,否则 npm 包里不会带这个文件。
43
+
44
+ ### 未采用(本仓库已自行实现)
45
+
46
+ - **缓存命中透传**:PR 里的 `pickUsage` 会挑字段重组 usage,覆盖面反而比本仓库
47
+ 0.8.x 起的实现更窄 —— 本仓库在 `protocol/sse.ts` 是**整体保留**上游 usage
48
+ (含 `prompt_tokens_details.cached_tokens`),并在 `server.ts` 里读取打日志。
49
+ - **自动签到调度器**(`src/checkin-scheduler.ts`):每分钟轮询、开机补跑、
50
+ 每天最多 3 次重试、默认开启。本版**不包含** —— 签到仍只由用户点击触发,
51
+ 不替用户自动改账号状态。需要的话建议后续以「默认关闭 + 显式开关」的方式加。
52
+
53
+ ### 内部
54
+
55
+ - `chatLog` 从 `server.ts` 抽到 `src/protocol/log.ts`(签到模块也要写同一个
56
+ `chat.log`,两处各写一份会互相交错)。
57
+ - 签到逻辑独立成 `src/checkin.ts`,纯函数可单测,不绑在 HTTP 层;
58
+ `server.ts` 已 1100+ 行,不再往里塞。
59
+ - `src/credit-expiry.ts` 只依赖一个极小的 `ExpiryInput` 接口,不 import `server.ts`。
60
+ - 单测 42 → **80**,新增 `tests/checkin-filter.spec.ts`(16 项)与
61
+ `tests/credit-expiry.spec.ts`(22 项)。
62
+
63
+ ## 0.9.1 — 2026-11-19
64
+
65
+ - 请求体超限返回 413 而不是 400。
66
+ - 上下文窗口改为如实上报真实值(系数 2.5 → 1.0),修掉「压缩失败」。
67
+
68
+ ## 0.9.0 — 2026-11-19
69
+
70
+ - 首个正式发布版本,插件市场上架。
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 XLNC-L
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -11,10 +11,11 @@
11
11
  | 部分 | 状态 |
12
12
  |---|---|
13
13
  | 协议逆向 | ✅ 全部实测确认 |
14
- | 密码层(ECDH / SM4-GCM / 签名) | ✅ 单测 7 项通过 |
14
+ | 密码层(ECDH / SM4-GCM / 签名) | ✅ 单测 18 项通过 |
15
15
  | 凭证(AK/SK → 自动换 STS) | ✅ 端到端验证 |
16
16
  | OpenAI 兼容 HTTP 服务 | ✅ 流式 + 非流式均验证 |
17
- | 前端设置面板 | ✅ 构建通过(19.5KB bundle) |
17
+ | 福利活动(签到 / 确认 / 到期预警) | ✅ 单测 38 项通过 |
18
+ | 前端设置面板 | ✅ 构建通过(50.4KB bundle) |
18
19
  | 输入框状态胶囊 | ✅ 构建通过 |
19
20
 
20
21
  **已实测打通**:`doctor` 四步全绿,HTTP 流式返回 `reasoning_content` + `content` + `[DONE]`,非流式返回完整 JSON。
@@ -228,6 +229,20 @@ lib/ 构建产物
228
229
 
229
230
  见 [`../RECON.md`](../RECON.md)。
230
231
 
232
+ ---
233
+
234
+ ## 致谢
235
+
236
+ - **[@vzhentian1-design](https://github.com/vzhentian1-design)** —— 0.9.2 的
237
+ `POST /v1/ops/confirm` 补全、多活动扫描 + `type`/`triggerEvent` 白名单、
238
+ 积分到期预警,以及 `LICENSE`,均来自他的
239
+ [PR #1](https://github.com/XLNC-L/dsh-connect-madao/pull/1)。
240
+ 四态状态机 `ELIGIBLE → CLAIMED → CONFIRMED → CONSUMED` 和
241
+ 「`confirm` 只认 `{campaignId}`、多带 `channel` 会 `400 HDN.1000`」
242
+ 这两条协议事实也是他先实测出来的。
243
+
244
+ 变更明细见 [CHANGELOG.md](./CHANGELOG.md)。
245
+
231
246
 
232
247
 
233
248
 
package/lib/client.js CHANGED
@@ -207,6 +207,26 @@ function CodeArtsPanel({ t }) {
207
207
  setCheckinBusy(false);
208
208
  }
209
209
  }, [checkinBusy, loadAccount]);
210
+ const doClaimAll = useCallback(async () => {
211
+ if (checkinBusy) return;
212
+ setCheckinBusy(true);
213
+ try {
214
+ const r = await bridgePost("/diag/checkin/all", {}, 9e4);
215
+ const got = Array.isArray(r?.claimed) ? r.claimed.length : 0;
216
+ setCheckin({
217
+ ok: true,
218
+ available: true,
219
+ claimAll: r,
220
+ reason: got > 0 ? t("checkin.allGot", { n: got }) : t("checkin.allNone")
221
+ });
222
+ void loadAccount();
223
+ void loadCheckin();
224
+ } catch (e) {
225
+ setCheckin({ ok: false, reason: String(e?.message ?? e) });
226
+ } finally {
227
+ setCheckinBusy(false);
228
+ }
229
+ }, [checkinBusy, loadAccount, loadCheckin, t]);
210
230
  useEffect(() => {
211
231
  void loadAccount();
212
232
  void loadCheckin();
@@ -459,14 +479,28 @@ function CodeArtsPanel({ t }) {
459
479
  acct.credit.used,
460
480
  "\uFF09"
461
481
  ] })
482
+ ] }) : null,
483
+ acct.creditExpiry ? /* @__PURE__ */ jsxs(Fragment, { children: [
484
+ /* @__PURE__ */ jsx("span", { style: S.detailKey, children: t("checkin.expiring") }),
485
+ /* @__PURE__ */ jsx(
486
+ "span",
487
+ {
488
+ style: {
489
+ ...S.detailVal,
490
+ color: acct.creditExpiry.level === "urgent" || acct.creditExpiry.level === "warn" ? "#d1242f" : "#d29922"
491
+ },
492
+ children: acct.creditExpiry.message
493
+ }
494
+ )
462
495
  ] }) : null
463
496
  ] }) : /* @__PURE__ */ jsx("div", { style: S.hint, children: t("account.noState") })
464
497
  ] }),
465
498
  /* @__PURE__ */ jsxs("div", { style: S.section, children: [
466
499
  /* @__PURE__ */ jsx("div", { style: S.sectionTitle, children: t("account.checkin") }),
467
500
  checkin && checkin.available !== false ? /* @__PURE__ */ jsxs("div", { style: { display: "flex", alignItems: "center", gap: 10 }, children: [
468
- /* @__PURE__ */ jsx("span", { style: { flex: 1, fontSize: 12 }, children: checkin.status === "CLAIMED" || checkin.status === "CONFIRMED" ? t("checkin.done", { n: checkin.amount ?? 100 }) : checkin.claimable ? t("checkin.available", { n: checkin.pendingAmount ?? 100 }) : t("checkin.idle") }),
469
- checkin.claimable ? /* @__PURE__ */ jsx("button", { style: S.btn(true), onClick: () => void doCheckin(), disabled: checkinBusy, children: checkinBusy ? t("checkin.doing") : t("checkin.claim") }) : null
501
+ /* @__PURE__ */ jsx("span", { style: { flex: 1, fontSize: 12 }, children: checkin.status === "CLAIMED" || checkin.status === "CONFIRMED" || checkin.status === "CONSUMED" ? t("checkin.done", { n: checkin.amount ?? 100 }) : checkin.claimable ? t("checkin.available", { n: checkin.pendingAmount ?? 100 }) : t("checkin.idle") }),
502
+ checkin.claimable ? /* @__PURE__ */ jsx("button", { style: S.btn(true), onClick: () => void doCheckin(), disabled: checkinBusy, children: checkinBusy ? t("checkin.doing") : t("checkin.claim") }) : null,
503
+ /* @__PURE__ */ jsx("button", { style: S.btn(false), onClick: () => void doClaimAll(), disabled: checkinBusy, children: checkinBusy ? t("checkin.allDoing") : t("checkin.all") })
470
504
  ] }) : /* @__PURE__ */ jsx("div", { style: S.hint, children: checkin?.reason ?? t("checkin.unavailable") })
471
505
  ] })
472
506
  ] }),
@@ -780,6 +814,11 @@ var zh = {
780
814
  "checkin.claim": "\u9886\u53D6",
781
815
  "checkin.doing": "\u9886\u53D6\u4E2D\u2026",
782
816
  "checkin.unavailable": "\u7B7E\u5230\u72B6\u6001\u6682\u65F6\u67E5\u8BE2\u4E0D\u5230",
817
+ "checkin.all": "\u9886\u5168\u90E8",
818
+ "checkin.allDoing": "\u9886\u53D6\u4E2D\u2026",
819
+ "checkin.allGot": "\u5DF2\u9886\u53D6 {n} \u9879\u6D3B\u52A8",
820
+ "checkin.allNone": "\u6CA1\u6709\u53EF\u9886\u7684\u6D3B\u52A8",
821
+ "checkin.expiring": "\u79EF\u5206\u5373\u5C06\u5230\u671F",
783
822
  "models.title": "\u53EF\u7528\u6A21\u578B",
784
823
  "models.hint": "\u4EE5\u4E0B\u6A21\u578B\u53D6\u81EA\u7801\u9053\u7F51\u5173\uFF0C\u5171 {n} \u4E2A\u3002",
785
824
  "models.name": "\u540D\u79F0",
@@ -873,6 +912,11 @@ var en = {
873
912
  "checkin.claim": "Claim",
874
913
  "checkin.doing": "Claiming\u2026",
875
914
  "checkin.unavailable": "Check-in status unavailable",
915
+ "checkin.all": "Claim all",
916
+ "checkin.allDoing": "Claiming\u2026",
917
+ "checkin.allGot": "Claimed {n} campaign(s)",
918
+ "checkin.allNone": "Nothing to claim",
919
+ "checkin.expiring": "Credits expiring soon",
876
920
  "models.title": "Available models",
877
921
  "models.hint": "{n} models from the CodeArts gateway.",
878
922
  "models.name": "Name",
package/lib/index.js CHANGED
@@ -82,11 +82,10 @@ var init_models = __esm({
82
82
  });
83
83
 
84
84
  // src/server.ts
85
- import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
85
+ import { createHash as createHash5 } from "node:crypto";
86
86
  import { createServer } from "node:http";
87
- import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
88
- import { homedir as homedir3 } from "node:os";
89
- import { join as join3 } from "node:path";
87
+ import { writeFileSync } from "node:fs";
88
+ import { join as join4 } from "node:path";
90
89
 
91
90
  // src/client.ts
92
91
  import { createHash as createHash3, randomUUID } from "node:crypto";
@@ -1620,6 +1619,236 @@ function parseStsIdentity(securityToken) {
1620
1619
  }
1621
1620
  }
1622
1621
 
1622
+ // src/credit-expiry.ts
1623
+ var WARN_DAYS = 7;
1624
+ var URGENT_DAYS = 2;
1625
+ function evaluateExpiry(credit, now = /* @__PURE__ */ new Date()) {
1626
+ if (!credit) return { level: "none", message: "", expiringAmount: 0, daysLeft: null, dueDate: null };
1627
+ const expiring = Number(credit.expiringAmount ?? 0);
1628
+ if (!Number.isFinite(expiring) || Math.round(expiring) <= 0) {
1629
+ return { level: "none", message: "", expiringAmount: 0, daysLeft: null, dueDate: null };
1630
+ }
1631
+ const due = parseDate(credit.packageEnd);
1632
+ const daysLeft = due ? Math.round((due.getTime() - startOfDay(now).getTime()) / 864e5) : null;
1633
+ let level = "info";
1634
+ if (daysLeft != null) {
1635
+ if (daysLeft <= URGENT_DAYS) level = "urgent";
1636
+ else if (daysLeft <= WARN_DAYS) level = "warn";
1637
+ } else {
1638
+ level = "info";
1639
+ }
1640
+ const amount = formatAmount(expiring);
1641
+ const when = daysLeft == null ? "\u5373\u5C06\u5230\u671F" : daysLeft <= 0 ? "\u5DF2\u5230\u671F" : `\u8FD8\u6709 ${daysLeft} \u5929\u5230\u671F\uFF08${credit.packageEnd}\uFF09`;
1642
+ return {
1643
+ level,
1644
+ expiringAmount: expiring,
1645
+ daysLeft,
1646
+ dueDate: credit.packageEnd ?? null,
1647
+ message: `${amount} \u79EF\u5206${when}\uFF0C\u8FC7\u671F\u5373\u6E05\u96F6`
1648
+ };
1649
+ }
1650
+ function startOfDay(d) {
1651
+ const x = new Date(d.getTime());
1652
+ x.setHours(0, 0, 0, 0);
1653
+ return x;
1654
+ }
1655
+ function parseDate(s) {
1656
+ if (!s) return null;
1657
+ const m = /^(\d{4})-(\d{2})-(\d{2})(?:$|[T\s])/.exec(String(s).trim());
1658
+ if (!m) return null;
1659
+ const month = Number(m[2]);
1660
+ const day = Number(m[3]);
1661
+ if (month < 1 || month > 12 || day < 1 || day > 31) return null;
1662
+ const d = new Date(Number(m[1]), month - 1, day);
1663
+ return Number.isNaN(d.getTime()) ? null : d;
1664
+ }
1665
+ function formatAmount(n) {
1666
+ return Math.round(n).toLocaleString("zh-CN");
1667
+ }
1668
+
1669
+ // src/checkin.ts
1670
+ import { randomUUID as randomUUID2 } from "node:crypto";
1671
+
1672
+ // src/protocol/log.ts
1673
+ import { appendFileSync, mkdirSync } from "node:fs";
1674
+ import { homedir as homedir3 } from "node:os";
1675
+ import { join as join3 } from "node:path";
1676
+ function logDir() {
1677
+ return join3(homedir3(), ".dsh-connect-madao");
1678
+ }
1679
+ function chatLog(line) {
1680
+ try {
1681
+ const dir = logDir();
1682
+ mkdirSync(dir, { recursive: true });
1683
+ appendFileSync(join3(dir, "chat.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
1684
+ `, "utf8");
1685
+ } catch {
1686
+ }
1687
+ }
1688
+
1689
+ // src/checkin.ts
1690
+ var DAILY_CHECKIN_CAMPAIGN = 34;
1691
+ function isCheckinCampaign(it) {
1692
+ if (!it) return false;
1693
+ const type = String(it?.type ?? "").toUpperCase();
1694
+ const event = String(it?.extra?.triggerEvent ?? "").toLowerCase();
1695
+ const title = String(it?.title ?? "");
1696
+ if (type === "USER_LOGIN") return true;
1697
+ if (event === "user.login") return true;
1698
+ return /签到/.test(title) && !/报名|认证|注册|邀请/.test(title);
1699
+ }
1700
+ function viewOf(it) {
1701
+ return {
1702
+ campaignId: Number(it?.campaignId),
1703
+ title: String(it?.title ?? `campaign=${it?.campaignId}`),
1704
+ type: it?.type ?? null,
1705
+ triggerEvent: it?.extra?.triggerEvent ?? null,
1706
+ triggerMode: it?.extra?.triggerMode ?? null,
1707
+ status: it?.status ?? null,
1708
+ claimable: it?.claimable === true,
1709
+ pendingAmount: Number(it?.pendingTotalAmount ?? 0),
1710
+ benefitAmount: Number(it?.benefitAmount ?? 0),
1711
+ benefitUnit: String(it?.benefitUnit ?? "CREDIT"),
1712
+ expireAt: it?.expireAt ?? null
1713
+ };
1714
+ }
1715
+ async function fetchCampaigns(client) {
1716
+ const d = await client.getJson("/v1/ops/delivery?channel=IDE");
1717
+ const items = d?.data?.items;
1718
+ return Array.isArray(items) ? items : [];
1719
+ }
1720
+ async function queryCheckin(client) {
1721
+ const items = await fetchCampaigns(client);
1722
+ const campaigns = items.map(viewOf);
1723
+ const daily = items.find((x) => Number(x?.campaignId) === DAILY_CHECKIN_CAMPAIGN);
1724
+ if (!daily) {
1725
+ return {
1726
+ ok: true,
1727
+ available: false,
1728
+ reason: "\u7F51\u5173\u7684\u798F\u5229\u5217\u8868\u91CC\u6CA1\u6709\u6BCF\u65E5\u7B7E\u5230\u6D3B\u52A8\uFF08campaignId=34\uFF09",
1729
+ campaigns
1730
+ };
1731
+ }
1732
+ const v = viewOf(daily);
1733
+ return {
1734
+ ok: true,
1735
+ available: true,
1736
+ campaignId: v.campaignId,
1737
+ title: v.title,
1738
+ status: v.status,
1739
+ claimable: v.claimable,
1740
+ pendingAmount: v.pendingAmount,
1741
+ unit: v.benefitUnit,
1742
+ expireAt: v.expireAt,
1743
+ campaigns
1744
+ };
1745
+ }
1746
+ async function claimCheckin(client) {
1747
+ const state = await queryCheckin(client);
1748
+ if (!state.available) return state;
1749
+ if (!state.claimable || state.status !== "ELIGIBLE") {
1750
+ const why = state.status === "CONSUMED" ? "\u4ECA\u65E5\u5DF2\u9886\u53D6\uFF08\u79EF\u5206\u5DF2\u7528\u5B8C\uFF09" : state.status === "CONFIRMED" ? "\u4ECA\u65E5\u5DF2\u9886\u53D6\uFF08\u5DF2\u5230\u8D26\uFF09" : state.status === "CLAIMED" ? "\u4ECA\u65E5\u5DF2\u9886\u53D6\uFF08\u5F85\u786E\u8BA4\uFF0C\u5DF2\u81EA\u52A8\u8865 confirm\uFF09" : "\u5F53\u524D\u4E0D\u53EF\u9886\u53D6";
1751
+ return { ...state, claimed: false, reason: `${why}\uFF08status=${state.status ?? "null"}\uFF09` };
1752
+ }
1753
+ const r = await client.postJson("/v1/ops/claim", {
1754
+ campaignId: DAILY_CHECKIN_CAMPAIGN,
1755
+ idempotentKey: randomUUID2(),
1756
+ channel: "IDE"
1757
+ });
1758
+ const claimed = r?.code === 0;
1759
+ chatLog(
1760
+ `checkin ${claimed ? "OK" : "FAIL"} campaign=${DAILY_CHECKIN_CAMPAIGN} ${JSON.stringify(r?.data ?? r).slice(0, 200)}`
1761
+ );
1762
+ if (claimed) await confirmClaim(client, DAILY_CHECKIN_CAMPAIGN);
1763
+ return {
1764
+ ...state,
1765
+ claimed,
1766
+ status: r?.data?.status ?? (claimed ? "CLAIMED" : state.status),
1767
+ amount: r?.data?.totalAmount ?? state.pendingAmount,
1768
+ claimedAt: r?.data?.claimedAt ?? null,
1769
+ ...claimed ? {} : { reason: String(r?.message ?? "\u9886\u53D6\u5931\u8D25") }
1770
+ };
1771
+ }
1772
+ async function confirmClaim(client, campaignId) {
1773
+ try {
1774
+ const r = await client.postJson("/v1/ops/confirm", { campaignId });
1775
+ const ok = r?.code === 0;
1776
+ chatLog(`confirm ${ok ? "OK" : "FAIL"} campaign=${campaignId} ${JSON.stringify(r?.data ?? r).slice(0, 160)}`);
1777
+ return ok;
1778
+ } catch (e) {
1779
+ chatLog(`confirm ERROR campaign=${campaignId} ${String(e?.message ?? e).slice(0, 160)}`);
1780
+ return false;
1781
+ }
1782
+ }
1783
+ async function claimAllCheckins(client) {
1784
+ const items = await fetchCampaigns(client);
1785
+ const campaigns = items.map(viewOf);
1786
+ const claimed = [];
1787
+ const skipped = [];
1788
+ for (const it of items) {
1789
+ const id = Number(it?.campaignId);
1790
+ const title = String(it?.title ?? `campaign=${id}`);
1791
+ const mode = it?.extra?.triggerMode;
1792
+ if (!Number.isFinite(id)) continue;
1793
+ if (mode === "AUTO_GRANT") {
1794
+ skipped.push({ campaignId: id, title, reason: "\u81EA\u52A8\u53D1\u653E\uFF0C\u65E0\u9700\u9886\u53D6" });
1795
+ continue;
1796
+ }
1797
+ if (it?.status === "CLAIMED") {
1798
+ const done = await confirmClaim(client, id);
1799
+ skipped.push({
1800
+ campaignId: id,
1801
+ title,
1802
+ reason: done ? "\u5DF2\u8865\u786E\u8BA4\uFF08\u6B64\u524D\u5DF2\u9886\u672A\u786E\u8BA4\uFF09" : "\u8865\u786E\u8BA4\u5931\u8D25\uFF0C\u4E0B\u8F6E\u518D\u8BD5"
1803
+ });
1804
+ continue;
1805
+ }
1806
+ if (!isCheckinCampaign(it)) {
1807
+ skipped.push({
1808
+ campaignId: id,
1809
+ title,
1810
+ reason: `\u975E\u7B7E\u5230\u7C7B\u6D3B\u52A8\uFF0C\u8DF3\u8FC7\u81EA\u52A8\u9886\u53D6\uFF08type=${it?.type ?? "-"}, event=${it?.extra?.triggerEvent ?? "-"}\uFF09`
1811
+ });
1812
+ continue;
1813
+ }
1814
+ if (!it?.claimable || it?.status !== "ELIGIBLE") {
1815
+ skipped.push({
1816
+ campaignId: id,
1817
+ title,
1818
+ reason: `\u5F53\u524D\u4E0D\u53EF\u9886\uFF08status=${it?.status ?? "null"}, claimable=${it?.claimable}\uFF09`
1819
+ });
1820
+ continue;
1821
+ }
1822
+ try {
1823
+ const r = await client.postJson("/v1/ops/claim", {
1824
+ campaignId: id,
1825
+ idempotentKey: randomUUID2(),
1826
+ channel: "IDE"
1827
+ });
1828
+ const ok = r?.code === 0;
1829
+ chatLog(`claimAll ${ok ? "OK" : "FAIL"} campaign=${id} ${JSON.stringify(r?.data ?? r).slice(0, 160)}`);
1830
+ if (ok) {
1831
+ const confirmed = await confirmClaim(client, id);
1832
+ claimed.push({
1833
+ campaignId: id,
1834
+ title,
1835
+ amount: Number(r?.data?.totalAmount ?? it?.pendingTotalAmount ?? it?.benefitAmount ?? 0),
1836
+ confirmed
1837
+ });
1838
+ } else {
1839
+ skipped.push({
1840
+ campaignId: id,
1841
+ title,
1842
+ reason: `${String(r?.message ?? "\u9886\u53D6\u5931\u8D25")}\uFF08code=${r?.code ?? "-"}\uFF09`
1843
+ });
1844
+ }
1845
+ } catch (e) {
1846
+ skipped.push({ campaignId: id, title, reason: String(e?.message ?? e) });
1847
+ }
1848
+ }
1849
+ return { ok: true, claimed, skipped, campaigns };
1850
+ }
1851
+
1623
1852
  // src/server.ts
1624
1853
  async function ensureFreshClient(ctx) {
1625
1854
  if (!ctx.sts || !ctx.loaded) return;
@@ -1734,48 +1963,8 @@ async function handle(req, res, ctx) {
1734
1963
  return json(res, 503, { error: { message: ctx.loadError ?? "\u51ED\u8BC1\u672A\u52A0\u8F7D", type: "credentials_error" } });
1735
1964
  }
1736
1965
  try {
1737
- const d = await ctx.client.getJson("/v1/ops/delivery?channel=IDE");
1738
- const items = d?.data?.items ?? [];
1739
- const daily = items.find((x) => x?.campaignId === 34);
1740
- if (!daily) {
1741
- return json(res, 200, {
1742
- ok: true,
1743
- available: false,
1744
- reason: "\u7F51\u5173\u7684\u798F\u5229\u5217\u8868\u91CC\u6CA1\u6709\u6BCF\u65E5\u7B7E\u5230\u6D3B\u52A8\uFF08campaignId=34\uFF09"
1745
- });
1746
- }
1747
- const state = {
1748
- campaignId: 34,
1749
- title: daily.title,
1750
- status: daily.status,
1751
- claimable: daily.claimable === true,
1752
- pendingAmount: daily.pendingTotalAmount ?? 0,
1753
- unit: daily.benefitUnit ?? "CREDIT",
1754
- expireAt: daily.expireAt ?? null
1755
- };
1756
- if (req.method === "GET") {
1757
- return json(res, 200, { ok: true, available: true, ...state });
1758
- }
1759
- if (!state.claimable || daily.status !== "ELIGIBLE") {
1760
- return json(res, 200, { ok: true, available: true, claimed: false, ...state, reason: "\u5F53\u524D\u4E0D\u53EF\u9886\u53D6" });
1761
- }
1762
- const r = await ctx.client.postJson("/v1/ops/claim", {
1763
- campaignId: 34,
1764
- idempotentKey: randomUUID2(),
1765
- channel: "IDE"
1766
- });
1767
- const claimed = r?.code === 0;
1768
- chatLog(`checkin ${claimed ? "OK" : "FAIL"} campaign=34 ${JSON.stringify(r?.data ?? r).slice(0, 200)}`);
1769
- return json(res, 200, {
1770
- ok: true,
1771
- available: true,
1772
- claimed,
1773
- ...state,
1774
- status: r?.data?.status ?? state.status,
1775
- amount: r?.data?.totalAmount ?? state.pendingAmount,
1776
- claimedAt: r?.data?.claimedAt ?? null,
1777
- ...claimed ? {} : { reason: String(r?.message ?? "\u9886\u53D6\u5931\u8D25") }
1778
- });
1966
+ const state = req.method === "GET" ? await queryCheckin(ctx.client) : await claimCheckin(ctx.client);
1967
+ return json(res, 200, state);
1779
1968
  } catch (e) {
1780
1969
  chatLog(`checkin ERROR ${String(e?.message ?? e).slice(0, 200)}`);
1781
1970
  return json(res, 502, {
@@ -1783,6 +1972,20 @@ async function handle(req, res, ctx) {
1783
1972
  });
1784
1973
  }
1785
1974
  }
1975
+ if (req.method === "POST" && url.pathname === "/diag/checkin/all") {
1976
+ await ensureFreshClient(ctx);
1977
+ if (!ctx.client) {
1978
+ return json(res, 503, { error: { message: ctx.loadError ?? "\u51ED\u8BC1\u672A\u52A0\u8F7D", type: "credentials_error" } });
1979
+ }
1980
+ try {
1981
+ return json(res, 200, await claimAllCheckins(ctx.client));
1982
+ } catch (e) {
1983
+ chatLog(`checkin/all ERROR ${String(e?.message ?? e).slice(0, 200)}`);
1984
+ return json(res, 502, {
1985
+ error: { message: `\u6279\u91CF\u7B7E\u5230\u5931\u8D25\uFF1A${String(e?.message ?? e)}`, type: "checkin_error" }
1986
+ });
1987
+ }
1988
+ }
1786
1989
  if (req.method === "POST" && url.pathname === "/diag/credentials") {
1787
1990
  let payload = {};
1788
1991
  try {
@@ -1896,15 +2099,6 @@ async function handle(req, res, ctx) {
1896
2099
  }
1897
2100
  json(res, 404, { error: { message: `\u672A\u77E5\u8DEF\u5F84 ${url.pathname}`, type: "not_found" } });
1898
2101
  }
1899
- function chatLog(line) {
1900
- try {
1901
- const dir = join3(homedir3(), ".dsh-connect-madao");
1902
- mkdirSync(dir, { recursive: true });
1903
- appendFileSync(join3(dir, "chat.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
1904
- `, "utf8");
1905
- } catch {
1906
- }
1907
- }
1908
2102
  var IMAGE_TOKEN_ESTIMATE = 1500;
1909
2103
  function estimateTokens(value) {
1910
2104
  let cjk = 0;
@@ -1999,7 +2193,7 @@ async function chatCompletion(res, client, rawBody, ctxModels) {
1999
2193
  const msgCount = Array.isArray(rawBody.messages) ? rawBody.messages.length : 0;
2000
2194
  chatLog(`chat REJECT body ${mb}MB (msgs ${msgCount} + tools ${toolCountForMsg}) > 9.5MB for ${model}`);
2001
2195
  const smaller = ctxModels.filter((m) => m.context <= 262144).slice(0, 4).map((m) => `${m.name}\uFF08${m.context}\uFF09`);
2002
- return json(res, 400, {
2196
+ return json(res, 413, {
2003
2197
  error: {
2004
2198
  message: `\u5F53\u524D\u4F1A\u8BDD\u7684\u8BF7\u6C42\u4F53 ${mb} MB\uFF0C\u8D85\u8FC7\u7801\u9053\u7F51\u5173\u7EA6 10 MB \u7684\u5355\u6B21\u4E0A\u9650\u3002
2005
2199
  \u8FD9\u4E0D\u662F\u914D\u7F6E\u95EE\u9898\uFF0C\u7F51\u5173\u4F1A\u8FD4\u56DE\u300C\u53C2\u6570\u65E0\u6548\u300D\u800C\u4E0D\u8BF4\u662F\u4F53\u79EF\u8D85\u4E86\u3002
@@ -2024,7 +2218,7 @@ async function chatCompletion(res, client, rawBody, ctxModels) {
2024
2218
  `chat REJECT context ${estTokens} (msgs ${estMessages} + tools ${estTools}/${toolCount}) > ${limit} for ${model}`
2025
2219
  );
2026
2220
  try {
2027
- writeFileSync(join3(homedir3(), ".dsh-connect-madao", "last-rejected.json"), JSON.stringify(rawBody), "utf8");
2221
+ writeFileSync(join4(logDir(), "last-rejected.json"), JSON.stringify(rawBody), "utf8");
2028
2222
  chatLog("chat REJECT \u8BF7\u6C42\u4F53\u5DF2\u5B58\u81F3 ~/.dsh-connect-madao/last-rejected.json");
2029
2223
  } catch {
2030
2224
  }
@@ -2225,6 +2419,16 @@ async function healthz(ctx) {
2225
2419
  function pickMetric(list, name2) {
2226
2420
  return list.find((m) => m?.name === name2);
2227
2421
  }
2422
+ function pickExpiring(list) {
2423
+ for (const name2 of ["usageTotalPackageCredit", "usageBonusPackageCredit"]) {
2424
+ const m = pickMetric(list, name2);
2425
+ if (m && m.package_credit_expiring_amount != null) {
2426
+ const n = Number(m.package_credit_expiring_amount);
2427
+ if (Number.isFinite(n) && n > 0) return n;
2428
+ }
2429
+ }
2430
+ return 0;
2431
+ }
2228
2432
  async function queryCredit(client) {
2229
2433
  try {
2230
2434
  const r = await client.getJson("/snap-manager/v1/statistics/plugin");
@@ -2240,7 +2444,12 @@ async function queryCredit(client) {
2240
2444
  basic: pkg(pickMetric(list, "usageBasicPackageCredit")),
2241
2445
  bonus: pkg(pickMetric(list, "usageBonusPackageCredit")),
2242
2446
  onDemand: pkg(pickMetric(list, "usageOnDemandPackageCredit")),
2243
- totalTokens: tokens ? Number(tokens.usage_token_num ?? 0) : void 0
2447
+ totalTokens: tokens ? Number(tokens.usage_token_num ?? 0) : void 0,
2448
+ // package_credit_expiring_amount 只在两个「汇总」指标上出现,
2449
+ // 分项指标(basic / onDemand)没有这个字段,所以取汇总那份。
2450
+ expiringAmount: pickExpiring(list),
2451
+ packageStart: typeof r?.start_date === "string" ? r.start_date : void 0,
2452
+ packageEnd: typeof r?.end_date === "string" ? r.end_date : void 0
2244
2453
  };
2245
2454
  } catch {
2246
2455
  return null;
@@ -2277,7 +2486,11 @@ async function accountInfo(ctx) {
2277
2486
  base.sts = stsExpiry ? { expiresAt: new Date(stsExpiry).toISOString(), ttlSec: Math.round((stsExpiry - Date.now()) / 1e3) } : "provided";
2278
2487
  base.sessionKey = { keyId: key.keyId, ttlSec: Math.round((key.expiresAt - Date.now()) / 1e3) };
2279
2488
  const credit = await queryCredit(ctx.client);
2280
- if (credit) base.credit = credit;
2489
+ if (credit) {
2490
+ base.credit = credit;
2491
+ const notice = evaluateExpiry(credit);
2492
+ if (notice.level !== "none") base.creditExpiry = notice;
2493
+ }
2281
2494
  try {
2282
2495
  const roles = await ctx.client.getJson("/snap-manager/v1/member/roles");
2283
2496
  base.roles = roles?.enterprise_roles ?? [];
@@ -2438,17 +2651,17 @@ function syncPatch(path, models) {
2438
2651
 
2439
2652
  // src/index.ts
2440
2653
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync2, existsSync as existsSync3 } from "node:fs";
2441
- import { dirname as dirname2, join as join4 } from "node:path";
2654
+ import { dirname as dirname2, join as join5 } from "node:path";
2442
2655
  import { homedir as homedir4 } from "node:os";
2443
2656
  import { fileURLToPath } from "node:url";
2444
2657
  var name = "dsh-connect-madao";
2445
2658
  var inject = [];
2446
2659
  var PROVIDER = "madao";
2447
2660
  function diag(line) {
2448
- const dir = join4(homedir4(), ".dsh-connect-madao");
2661
+ const dir = join5(homedir4(), ".dsh-connect-madao");
2449
2662
  try {
2450
2663
  mkdirSync2(dir, { recursive: true });
2451
- appendFileSync2(join4(dir, "host.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
2664
+ appendFileSync2(join5(dir, "host.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
2452
2665
  `, "utf8");
2453
2666
  } catch {
2454
2667
  }
@@ -2460,11 +2673,11 @@ function diag(line) {
2460
2673
  function patchPath() {
2461
2674
  try {
2462
2675
  const here = dirname2(fileURLToPath(import.meta.url));
2463
- const candidate = join4(here, "..", "cordis.patch.yml");
2676
+ const candidate = join5(here, "..", "cordis.patch.yml");
2464
2677
  if (existsSync3(candidate) || existsSync3(dirname2(candidate))) return candidate;
2465
2678
  } catch {
2466
2679
  }
2467
- return join4(process.cwd(), "cordis.patch.yml");
2680
+ return join5(process.cwd(), "cordis.patch.yml");
2468
2681
  }
2469
2682
  function apply(ctx, config = {}) {
2470
2683
  diag(`apply() called; enabled=${config.enabled} port=${config.port ?? 8765}`);
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "dsh-connect-madao",
3
3
  "displayName": "DSH Connect 码道",
4
4
  "description": "把华为云码道(CodeArts Agent)的模型接入 DeepSeek Harness:自签 SDK-HMAC-SHA256、P-256 密钥协商与 SM4-GCM 载荷加密,对外提供 OpenAI 兼容接口,并带设置面板与状态胶囊。",
5
- "version": "0.9.0",
5
+ "version": "0.9.2",
6
6
  "license": "MIT",
7
7
  "type": "module",
8
8
  "engines": {
@@ -29,6 +29,8 @@
29
29
  "icons",
30
30
  "locale",
31
31
  "cordis.patch.yml",
32
+ "LICENSE",
33
+ "CHANGELOG.md",
32
34
  "README.md",
33
35
  "INSTALL.md",
34
36
  "FAQ.md"