@dsh-mobile/mobile-remote 0.0.0-stage → 3.2.5

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 (73) hide show
  1. package/CHANGELOG.md +1273 -0
  2. package/CONTRIBUTING.md +59 -0
  3. package/FAQ.md +115 -0
  4. package/LICENSE +21 -0
  5. package/README.md +293 -2
  6. package/cordis.patch.yml +22 -0
  7. package/docs/00-/345/274/200/345/217/221/346/200/273/347/272/262.md +121 -0
  8. package/docs/01-PRD.md +148 -0
  9. package/docs/02-architecture.md +249 -0
  10. package/docs/03-api.md +882 -0
  11. package/docs/04-security.md +109 -0
  12. package/docs/05-test-cases.md +376 -0
  13. package/docs/06-install-run.md +349 -0
  14. package/docs/07-user-manual.md +92 -0
  15. package/docs/08-/346/211/251/345/261/225/345/274/200/345/217/221/346/214/207/345/215/227.md +86 -0
  16. package/docs/09-compatibility.md +201 -0
  17. package/docs/10-remote-access-and-launch-plan.md +216 -0
  18. package/docs/11-remote-relay-guide.md +82 -0
  19. package/docs/APP-ENCRYPTION-DESCRIPTION.md +50 -0
  20. package/docs/APP-ENCRYPTION-DESCRIPTION.pdf +0 -0
  21. package/docs/ARCHITECTURE-CURRENT.md +229 -0
  22. package/docs/AUDIT-2026-11-node.md +181 -0
  23. package/docs/AUDIT-2026-11.md +167 -0
  24. package/docs/BRAND-ASSETS.md +142 -0
  25. package/docs/BUILD-ENVIRONMENT.md +180 -0
  26. package/docs/FEATURE-PARITY.md +195 -0
  27. package/docs/PRIVACY-POLICY.en.md +143 -0
  28. package/docs/PRIVACY-POLICY.md +143 -0
  29. package/docs/REA-UNDERSTANDING.md +246 -0
  30. package/docs/STORE-LAUNCH.md +278 -0
  31. package/docs/STORE-LISTING.md +150 -0
  32. package/docs/SUPPORT.md +43 -0
  33. package/docs/TERMS-OF-SERVICE.en.md +70 -0
  34. package/docs/TERMS-OF-SERVICE.md +70 -0
  35. package/docs/screenshots/01-home.png +0 -0
  36. package/docs/screenshots/02-notifications.png +0 -0
  37. package/docs/screenshots/03-sessions.png +0 -0
  38. package/docs/screenshots/04-chat.png +0 -0
  39. package/docs/screenshots/05-settings.png +0 -0
  40. package/docs/screenshots/06-new-session.png +0 -0
  41. package/docs/screenshots/07-connect.png +0 -0
  42. package/docs/screenshots/pgy-appstore.jpg +0 -0
  43. package/docs/screenshots/pgy-mobile-app.jpg +0 -0
  44. package/docs/screenshots/pgy-pc-client.jpg +0 -0
  45. package/lib/account-usage-query.js +278 -0
  46. package/lib/account-usage.js +145 -0
  47. package/lib/api-helpers.js +333 -0
  48. package/lib/auto-config.js +107 -0
  49. package/lib/client.js +586 -0
  50. package/lib/config.js +211 -0
  51. package/lib/git-read-bundled-provider.js +255 -0
  52. package/lib/git-read-service.js +322 -0
  53. package/lib/host-compat.js +133 -0
  54. package/lib/http-util.js +69 -0
  55. package/lib/index.js +5729 -0
  56. package/lib/push.js +73 -0
  57. package/lib/rate-limit.js +46 -0
  58. package/lib/relay/connector.js +300 -0
  59. package/lib/relay/crypto.js +117 -0
  60. package/lib/relay/devices.js +138 -0
  61. package/lib/relay/identity.js +60 -0
  62. package/lib/relay/mux.js +411 -0
  63. package/lib/relay/noise.js +178 -0
  64. package/lib/relay/pairing.js +64 -0
  65. package/lib/relay/phone.js +114 -0
  66. package/lib/relay/serve.js +105 -0
  67. package/lib/rpc-adapter.js +88 -0
  68. package/lib/session-list.js +77 -0
  69. package/lib/session-title-cache.js +123 -0
  70. package/lib/session-title-refresh.js +261 -0
  71. package/lib/timeline.js +476 -0
  72. package/lib/turn-outline.js +289 -0
  73. package/package.json +62 -4
@@ -0,0 +1,70 @@
1
+ # DSH Mobile - DeepSeek Harness 服务条款
2
+
3
+ > 生效日期:2026-11-02 · 最近更新:2026-11-02
4
+ > 发布者:Digital Bang Intelligence LLC.,30 N Gould St Ste R, Sheridan, WY 82801, USA · support@claud.ing
5
+
6
+ ## 1. 协议
7
+
8
+ 本条款是你与 Digital Bang Intelligence LLC.(以下称“我们”)之间,关于你使用 DSH Mobile - DeepSeek Harness(以下称“DSH Mobile”或“本应用”)及网站 dsh.claud.ing 的协议。安装或使用本应用,即表示你同意本条款;如果不同意,请不要使用。我们如何处理信息,见[隐私政策](/privacy/)。
9
+
10
+ ## 2. 本应用是什么
11
+
12
+ DSH Mobile 是 DeepSeek Harness 的独立移动伴侣,与 DeepSeek 没有隶属或背书关系。它连接到你在自己电脑上安装并运行的 DeepSeek Harness 服务,让你查看和继续会话、查看任务、回答问询、审批工具动作、浏览工作区文件和接收提醒。使用前,你的电脑上需要有 DeepSeek Harness 和 DSH Mobile 插件,并且手机和电脑要能在同一个可信网络中互相访问。
13
+
14
+ “DeepSeek”及相关名称归其所有者所有,在这里只用于说明本应用配合使用的对象。
15
+
16
+ ## 3. 许可
17
+
18
+ 我们授予你一项个人的、非独占的、不可转让的、可撤销的许可:在你拥有或控制的设备上,为你自己使用而安装和使用本应用,并遵守本条款。你不得复制、出售、出租或转授权本应用,不得用它违反法律或侵害他人权利,不得干扰它的运行,也不得尝试访问你无权访问的系统。
19
+
20
+ 本项目的源代码以及本应用使用的开源组件,各自适用其自己的许可(本项目自己的源代码采用 MIT 许可)。本条款不限制这些许可赋予你的权利。
21
+
22
+ ## 4. 你的责任
23
+
24
+ - **你的电脑和网络。** 应用连接的是你自己运行的服务。你要对那台电脑、谁能访问它、以及访问口令和二维码的保密负责。请只在可信网络中使用连接。
25
+ - **审批工具动作。** 当 AI 智能体请求运行命令或修改文件,而你在应用里批准后,这个动作会以你的权限在你的电脑上执行。请看清楚再批准。你批准的动作,我们不承担责任。
26
+ - **AI 输出。** 通过 DeepSeek Harness 及其模型提供商生成的回复可能有错、不完整或不安全。在依赖它们或运行它们建议的内容之前,请先自己核对。
27
+ - **其他服务。** DeepSeek Harness、模型提供商和你配置的推送通道由他人按各自的条款和费用提供,你使用它们时适用这些条款。
28
+
29
+ ## 5. 价格和购买
30
+
31
+ DSH Mobile 目前免费。如果我们日后提供付费功能,会在你购买前于应用商店中展示价格和条款,并由 Apple 或 Google 按其条款处理付款。
32
+
33
+ ## 6. 隐私
34
+
35
+ 本应用没有账号、没有分析 SDK,也不会把你的会话、文件或凭据发送给我们。应用首页会展示一条由第三方广告网络提供的广告,广告请求不含你的会话内容。详情见[隐私政策](/privacy/)。
36
+
37
+ ## 7. 知识产权
38
+
39
+ 除第 3 节所述的开源许可外,本应用的名称、标志和美术作品归我们或我们的许可方所有。你对自己的内容(包括会话、文件和图片)保留全部权利;我们不会收到这些内容,也不主张任何权利。
40
+
41
+ ## 8. 免责声明
42
+
43
+ 在法律允许的最大范围内,本应用按“现状”和“可用”状态提供,不附带任何明示或暗示的保证,包括适销性、特定用途适用性、不侵权,以及不间断或无错误运行。我们不保证本应用能配合每个版本的 DeepSeek Harness、每种网络或每台设备使用。
44
+
45
+ ## 9. 责任限制
46
+
47
+ 在法律允许的最大范围内,对于因你使用本应用或通过它批准的动作而产生的任何间接、附带、特殊、后果性或惩罚性损害,以及数据、利润或业务的损失,我们不承担责任。我们就与本应用有关的任何索赔承担的全部责任,以索赔前 12 个月内你为本应用向我们支付的金额与 50 美元中较高者为限。部分地区不允许某些限制;在这种情况下,上述限制在法律允许的范围内适用,你依法享有的强制性消费者权利不受影响。
48
+
49
+ ## 10. 终止
50
+
51
+ 你可以随时卸载本应用以停止使用。如果你违反本条款,或我们不再提供本应用,我们可以暂停或终止你的使用。依其性质应在终止后继续有效的条款,在终止后继续有效。
52
+
53
+ ## 11. Apple App Store
54
+
55
+ 如果你从 Apple App Store 下载本应用,Apple 的标准《授权应用程序最终用户许可协议》同样适用;在 iOS 特有的事项上,如与本条款冲突,以 Apple 的条款为准。本条款只在你与我们之间成立,Apple 不是一方。本应用、支持服务以及与本应用有关的任何索赔,由我们而不是 Apple 负责。Apple 及其子公司是本条款的第三方受益人,可以向你执行本条款。
56
+
57
+ ## 12. 条款更新
58
+
59
+ 我们可能不时更新本条款。更新时,我们会修改本页顶部的日期,并在 dsh.claud.ing/terms/ 发布新文本。变更生效后你继续使用本应用,即表示接受更新后的条款。
60
+
61
+ ## 13. 适用法律
62
+
63
+ 本条款适用美国怀俄明州法律,不考虑其法律冲突规则。任何争议将在位于怀俄明州的州法院或联邦法院提起;但如果你所在地的强制性法律赋予你在别处起诉的权利,则从其规定。
64
+
65
+ ## 14. 联系我们
66
+
67
+ - 公司:Digital Bang Intelligence LLC.
68
+ - 地址:30 N Gould St Ste R, Sheridan, WY 82801, USA
69
+ - 邮箱:support@claud.ing
70
+ - 网站:[dsh.claud.ing](https://dsh.claud.ing)
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,278 @@
1
+ /**
2
+ * 账户用量与额度的上游查询(DeepSeek 余额 / Codex / OpenCode Go)。归一化纯函数在 account-usage.js。
3
+ * 从 lib/index.js 原样拆出(行为不变)。
4
+ */
5
+ import { credentialRef } from "@deepseek-ai/dsh-credentials";
6
+ import { createRequire } from "node:module";
7
+ import { homedir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { pathToFileURL } from "node:url";
10
+ import { normalizeCodexUsage, normalizeDeepSeekBalance, normalizeOpenCodeUsage } from "./account-usage.js";
11
+ import { safeFailureReason } from "./api-helpers.js";
12
+ import { readSettingsSection, readSettingsSectionStrict } from "./host-compat.js";
13
+
14
+ /** 与 PC 端设置页一致的凭据引用派生规则(v2.6):路由 id 大写 → `<ID>_API_KEY`。 */
15
+ export function deriveKeyRef(provider) {
16
+ return `${String(provider).toUpperCase().replace(/[^A-Z0-9]+/g, "_")}_API_KEY`;
17
+ }
18
+
19
+ async function resolveCredentialValue(ctx, ref) {
20
+ let value;
21
+ try {
22
+ const credentials = ctx.get("credentials");
23
+ if (credentials?.resolve) value = (await credentials.resolve(credentialRef(ref)))?.value;
24
+ } catch {
25
+ // 环境变量兜底;不把凭据服务异常暴露给手机端。
26
+ }
27
+ if ((!value || typeof value !== "string") && typeof process.env[ref] === "string") value = process.env[ref];
28
+ return typeof value === "string" && value.trim() !== "" ? value : undefined;
29
+ }
30
+
31
+ async function resolveOpenCodeCredential(ctx, profileRef) {
32
+ const validRef = (value) => typeof value === "string"
33
+ && value !== "DEEPSEEK_API_KEY"
34
+ && /^[A-Za-z_][A-Za-z0-9_]*$/.test(value);
35
+ if (validRef(profileRef)) {
36
+ const explicit = await resolveCredentialValue(ctx, profileRef);
37
+ if (explicit) return explicit;
38
+ }
39
+ try {
40
+ const credentials = ctx?.get?.("credentials");
41
+ const record = typeof credentials?.readRecord === "function"
42
+ ? await credentials.readRecord("llm-pi-ai/opencode-go")
43
+ : undefined;
44
+ if (record?.kind === "api-key" && typeof record.key === "string" && record.key.trim() !== "") return record.key;
45
+ } catch {
46
+ // 旧版 credentials 服务没有 readRecord 时继续走引用/环境变量回退。
47
+ }
48
+ for (const ref of ["OPENCODE_GO_API_KEY", "OPENCODE_API_KEY"]) {
49
+ const fallback = await resolveCredentialValue(ctx, ref);
50
+ if (fallback) return fallback;
51
+ }
52
+ return undefined;
53
+ }
54
+
55
+ async function loadCodexConnect() {
56
+ let bareError;
57
+ try {
58
+ return await import("dsh-codex-connect");
59
+ } catch (error) {
60
+ bareError = error;
61
+ }
62
+ const dshHome = typeof process.env.DSH_HOME === "string" && process.env.DSH_HOME.trim() !== ""
63
+ ? process.env.DSH_HOME
64
+ : join(homedir(), ".dsh");
65
+ for (const profile of ["web", "desktop", "cli"]) {
66
+ try {
67
+ const profileRequire = createRequire(join(dshHome, "profiles", profile, "package.json"));
68
+ const entry = profileRequire.resolve("dsh-codex-connect");
69
+ return await import(pathToFileURL(entry).href);
70
+ } catch {
71
+ // 继续尝试其他 DSH profile;缺失时最终按“未安装”处理。
72
+ }
73
+ }
74
+ throw bareError;
75
+ }
76
+
77
+ async function queryDeepSeekUsage(ctx) {
78
+ const key = await resolveCredentialValue(ctx, "DEEPSEEK_API_KEY");
79
+ if (!key) return { configured: false };
80
+ try {
81
+ const response = await fetch("https://api.deepseek.com/user/balance", {
82
+ headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
83
+ signal: AbortSignal.timeout(15_000),
84
+ });
85
+ if (!response.ok) {
86
+ await response.body?.cancel();
87
+ return { configured: true, failed: true, failedId: "deepseek", failedReason: `HTTP ${response.status}` };
88
+ }
89
+ const data = await response.json();
90
+ const balance = normalizeDeepSeekBalance(data);
91
+ return {
92
+ configured: true,
93
+ source: {
94
+ id: "deepseek",
95
+ title: "DeepSeek",
96
+ kind: "balance",
97
+ ...balance,
98
+ },
99
+ };
100
+ } catch (err) {
101
+ return { configured: true, failed: true, failedId: "deepseek", failedReason: safeFailureReason(err) };
102
+ }
103
+ }
104
+
105
+ /**
106
+ * 读取 Codex 代理配置(导出以便单测:issue #21 的回归点正在这里)。
107
+ *
108
+ * 返回值三态,**必须区分**:
109
+ * - `{ enabled: false }` —— 设置读得到,但用户没开代理(走直连是正确的);
110
+ * - `{ enabled: true, url }` —— 代理已启用且地址有效;
111
+ * - `{ enabled: true, url: undefined, unreadable: true }` —— **读不到宿主设置**。
112
+ * 这是插件与宿主的接口问题,不是用户的选择;原实现把它误判为"代理未启用",
113
+ * 于是静默改走直连、最终以"Codex 余额消失"的形式暴露,根因完全不可见。
114
+ */
115
+ export function codexProxyUrl(ctx, mod) {
116
+ const namespace = mod.OPENAI_CODEX_SETTINGS_NAMESPACE ?? "llm-openai-codex";
117
+ let settingsSvc;
118
+ try {
119
+ settingsSvc = ctx?.get?.("settings");
120
+ } catch {
121
+ settingsSvc = undefined;
122
+ }
123
+ // issue #21:原实现用 `settings.get()` 读该命名空间,而宿主 0.2.0 **移除了该方法**
124
+ // (同一处破坏在 issue #19 已修过另两个调用点,这一处因是可选链写法 `?.get?.(` 被漏掉)。
125
+ // 更要紧的是**语义**:读不到配置 ≠ 代理未启用。原实现把前者当作后者 → 返回 enabled:false
126
+ // → 插件静默改走直连 chatgpt.com → 连接超时 → 表现为"手机看不到 Codex 余额",
127
+ // 而配置本身(enableProxy:true + proxyUrl)一直好好的,用户完全看不出根因。
128
+ //
129
+ // 评审 WARNING 3 的补充:仅判断"读取方法存在"不够——`get()` 抛错、`describe()` 抛错、
130
+ // 或 describe 返回形状不合法时,宽松读取会把它们一律折叠成 undefined,再由 `?? {}`
131
+ // 伪装成"命名空间不存在"。故此处用**严格读取**,只有"读取成功且命名空间确实不存在"
132
+ // 才允许判定为"用户没开代理"。
133
+ const read = readSettingsSectionStrict(settingsSvc, namespace);
134
+ if (!read.ok) return { enabled: true, url: undefined, unreadable: true, reason: read.reason };
135
+ const settings = read.value ?? {};
136
+ try {
137
+ const resolved = typeof mod.resolveOpenAICodexSettings === "function"
138
+ ? mod.resolveOpenAICodexSettings(settings)
139
+ : settings;
140
+ const enabled = resolved?.enableProxy === true || settings?.enableProxy === true;
141
+ // 命名空间确实不存在 ⇒ 用户没开代理,走直连是正确行为(区别于上面的"读不了")
142
+ if (!enabled) return { enabled: false, url: undefined };
143
+ const url = typeof mod.resolveOpenAICodexProxyUrl === "function"
144
+ ? mod.resolveOpenAICodexProxyUrl(resolved)
145
+ : resolved?.proxyUrl;
146
+ return { enabled: true, url: typeof url === "string" && url.trim() !== "" ? url : undefined };
147
+ } catch {
148
+ return { enabled: true, url: undefined, unreadable: true, reason: "settings-resolve-threw" };
149
+ }
150
+ }
151
+
152
+ async function queryCodexUsage(ctx) {
153
+ let mod;
154
+ try {
155
+ mod = await loadCodexConnect();
156
+ } catch {
157
+ return { configured: false };
158
+ }
159
+ if (typeof mod?.OpenAICodexCredentialStore !== "function"
160
+ || typeof mod?.openAICodexAuthStatus !== "function"
161
+ || typeof mod?.readOpenAICodexRateLimits !== "function") return { configured: false };
162
+ let store;
163
+ let captured;
164
+ let proxyManager;
165
+ try {
166
+ store = new mod.OpenAICodexCredentialStore();
167
+ // 新版返回同一账户快照;旧版没有该方法时仍可读取额度,但账户标签降级为可选。
168
+ captured = typeof store.captureActiveAccount === "function" ? await store.captureActiveAccount() : store;
169
+ if (!captured) return { configured: false };
170
+ const status = await mod.openAICodexAuthStatus(captured);
171
+ if (status?.authenticated !== true) return { configured: false };
172
+ const proxy = codexProxyUrl(ctx, mod);
173
+ if (proxy.enabled && (!proxy.url || typeof mod.OpenAICodexProxyManager !== "function")) {
174
+ // v3.1.6(issue #21):**必须区分**「读不到宿主配置」与「用户没开代理」。
175
+ // 前者是插件与宿主的接口问题,后者是用户的选择;原实现把两者都归为 failed,
176
+ // 于是 Codex 余额整块消失而原因无法归因(见 failedReason 的两种措辞)。
177
+ return {
178
+ configured: true, failed: true, failedId: "codex",
179
+ failedReason: proxy.unreadable
180
+ ? "读不到宿主设置(settings 服务没有可用的读取方法),无法判断 Codex 代理配置"
181
+ : (proxy.url ? "宿主未提供代理管理器" : "代理已启用但未配置代理地址"),
182
+ };
183
+ }
184
+ proxyManager = proxy.enabled ? new mod.OpenAICodexProxyManager() : undefined;
185
+ const readUsage = () => mod.readOpenAICodexRateLimits(captured);
186
+ const usage = normalizeCodexUsage(proxyManager ? await proxyManager.run(proxy.url, readUsage) : await readUsage());
187
+ let active;
188
+ try {
189
+ const accounts = typeof captured.accounts === "function" ? await captured.accounts() : [];
190
+ active = Array.isArray(accounts) ? accounts.find((account) => account?.active === true) : undefined;
191
+ } catch {
192
+ // 账户标签是可选展示信息;额度投影成功时不因标签读取失败而隐藏来源。
193
+ }
194
+ return {
195
+ configured: true,
196
+ source: {
197
+ id: "codex",
198
+ title: "Codex",
199
+ kind: "quota",
200
+ ...usage,
201
+ ...(active && (active.displayName || active.maskedEmail) ? {
202
+ account: {
203
+ ...(typeof active.displayName === "string" && active.displayName !== "" ? { displayName: active.displayName } : {}),
204
+ ...(typeof active.maskedEmail === "string" && active.maskedEmail !== "" ? { maskedEmail: active.maskedEmail } : {}),
205
+ },
206
+ } : {}),
207
+ },
208
+ };
209
+ } catch (err) {
210
+ // v3.1.6(issue #21):失败原因要能对上号(此前只记 failed,用户无从判断是网络、
211
+ // 凭据还是插件读不到宿主配置)。detail 走脱敏。
212
+ return { configured: true, failed: true, failedId: "codex", failedReason: safeFailureReason(err) };
213
+ } finally {
214
+ try {
215
+ await proxyManager?.dispose?.();
216
+ } catch {
217
+ // 代理池释放失败不应掩盖已拿到的额度快照。
218
+ }
219
+ }
220
+ }
221
+
222
+ async function queryOpenCodeUsage(ctx) {
223
+ let profile;
224
+ try {
225
+ // issue #21:与 codexProxyUrl 同一种写法(可选链),同样受"0.2.0 移除 settings.get()"影响。
226
+ // 此处目前**碰巧仍有数据**(额度走的是凭据解析路径,profile 只用于取 apiKeyEnv),
227
+ // 但同一形式的读取必须一并改为跨代版本——否则换个宿主版本就会静默失效。
228
+ const settingsSvc = ctx?.get?.("settings");
229
+ const section = readSettingsSection(settingsSvc, "llm-pi-ai");
230
+ profile = section?.providers?.["opencode-go"];
231
+ } catch {
232
+ profile = undefined;
233
+ }
234
+ const key = await resolveOpenCodeCredential(ctx, profile?.apiKeyEnv);
235
+ if (!key) return { configured: false };
236
+ // 不接受设置页可配置的 baseURL,避免把套餐密钥发送到非官方/内网地址。
237
+ const url = "https://opencode.ai/zen/go/v1/usage";
238
+ try {
239
+ const response = await fetch(url, {
240
+ headers: { authorization: `Bearer ${key}`, accept: "application/json" },
241
+ signal: AbortSignal.timeout(15_000),
242
+ });
243
+ if (!response.ok) {
244
+ await response.body?.cancel();
245
+ return { configured: true, failed: true, failedId: "opencode-go", failedReason: `HTTP ${response.status}` };
246
+ }
247
+ const source = normalizeOpenCodeUsage(await response.json());
248
+ return { configured: true, source: { id: "opencode-go", title: "OpenCode Go", kind: "quota", ...source } };
249
+ } catch (err) {
250
+ return { configured: true, failed: true, failedId: "opencode-go", failedReason: safeFailureReason(err) };
251
+ }
252
+ }
253
+
254
+ export async function queryAccountUsage(ctx) {
255
+ const results = await Promise.all([
256
+ queryDeepSeekUsage(ctx),
257
+ queryCodexUsage(ctx),
258
+ queryOpenCodeUsage(ctx),
259
+ ]);
260
+ const sources = results.filter((result) => result?.source).map((result) => result.source);
261
+ const failures = results.filter((result) => result?.configured === true && result?.failed === true);
262
+ return {
263
+ ok: true,
264
+ fetchedAt: new Date().toISOString(),
265
+ sources,
266
+ availableCount: sources.length,
267
+ failedCount: failures.length,
268
+ // v3.1.6(issue #21):此前只给 failedCount。用户看到的是「Codex 整块消失」,
269
+ // 却无法判断是凭据没配、网络不通、还是插件读不到宿主配置——定位只能靠猜。
270
+ // 现在把**哪个来源失败、为什么失败**一并给出(无失败时省略该字段,保持响应稳定)。
271
+ ...(failures.length > 0 ? {
272
+ failures: failures.map((result) => ({
273
+ id: result.failedId ?? "unknown",
274
+ reason: result.failedReason ?? "未提供原因",
275
+ })),
276
+ } : {}),
277
+ };
278
+ }
@@ -0,0 +1,145 @@
1
+ // 用量与额度领域归一化:保持无运行时依赖,便于服务端单测与其它宿主复用。
2
+
3
+ /** 额度窗口标签:优先使用 provider 约定名称,未知窗口保持稳定可读。 */
4
+ export function usageWindowLabel(seconds) {
5
+ const value = Number(seconds);
6
+ if (!Number.isFinite(value) || value <= 0) return null;
7
+ if (value === 18_000) return '5h';
8
+ if (value === 604_800) return 'weekly';
9
+ if (value === 2_592_000) return 'monthly';
10
+ if (value % 604_800 === 0) return `${value / 604_800}w`;
11
+ if (value % 3_600 === 0) return `${value / 3_600}h`;
12
+ if (value % 60 === 0) return `${value / 60}m`;
13
+ return `${value}s`;
14
+ }
15
+
16
+ function finiteNumber(value) {
17
+ if (value === null || value === undefined || value === '' || typeof value === 'boolean') return undefined;
18
+ const number = typeof value === 'number' ? value : Number(value);
19
+ return Number.isFinite(number) ? number : undefined;
20
+ }
21
+
22
+ function clampPercent(value) {
23
+ const number = finiteNumber(value);
24
+ return number === undefined || number < 0 || number > 100 ? undefined : number;
25
+ }
26
+
27
+ function isoFromUnixSeconds(value) {
28
+ const seconds = finiteNumber(value);
29
+ if (seconds === undefined || seconds <= 0) return undefined;
30
+ const date = new Date(seconds * 1000);
31
+ return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
32
+ }
33
+
34
+ function isoFromDate(value) {
35
+ if (typeof value !== 'string' || value.trim() === '') return undefined;
36
+ const date = new Date(value);
37
+ return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
38
+ }
39
+
40
+ /** DeepSeek /user/balance 的顶层投影;优先选择 CNY 余额项。 */
41
+ export function normalizeDeepSeekBalance(data) {
42
+ const infos = data && typeof data === 'object' && !Array.isArray(data) ? data.balance_infos : undefined;
43
+ const validInfos = Array.isArray(infos) ? infos.filter((item) => item && typeof item === 'object' && !Array.isArray(item)) : [];
44
+ const first = validInfos.find((item) => item.currency === 'CNY') ?? validInfos[0];
45
+ const amount = first ? finiteNumber(first.total_balance) : undefined;
46
+ if (!first || amount === undefined) throw new Error('invalid deepseek balance');
47
+ return {
48
+ amount: String(first.total_balance),
49
+ currency: typeof first.currency === 'string' && first.currency !== '' ? first.currency : 'CNY',
50
+ available: data.is_available !== false && first.is_available !== false,
51
+ };
52
+ }
53
+
54
+ /**
55
+ * dsh-codex-connect 的无密钥投影 → 手机额度领域模型。
56
+ * 保留主 bucket 与 additional_rate_limits 的全部有效窗口,仅返回百分比/金额/窗口,不接触 OAuth token。
57
+ */
58
+ export function normalizeCodexUsage(usage) {
59
+ if (!usage || typeof usage !== 'object' || Array.isArray(usage)) throw new Error('invalid codex usage');
60
+ if (usage.rateLimits !== undefined && !Array.isArray(usage.rateLimits)) throw new Error('invalid codex rate limits');
61
+ const rateLimits = (usage.rateLimits ?? []).filter((bucket) => bucket && typeof bucket === 'object' && !Array.isArray(bucket));
62
+ const primaryIndex = rateLimits.findIndex((bucket) => bucket.id === 'codex');
63
+ const orderedBuckets = primaryIndex >= 0
64
+ ? [rateLimits[primaryIndex], ...rateLimits.filter((_, index) => index !== primaryIndex)]
65
+ : rateLimits;
66
+ const windows = [];
67
+ for (const [bucketIndex, bucket] of orderedBuckets.entries()) {
68
+ if (!Array.isArray(bucket.windows)) continue;
69
+ const bucketName = typeof bucket.name === 'string' && bucket.name.trim() !== ''
70
+ ? bucket.name.trim().slice(0, 80)
71
+ : typeof bucket.id === 'string' && bucket.id.trim() !== '' ? bucket.id.trim().slice(0, 80) : undefined;
72
+ const seenInBucket = new Set();
73
+ for (const item of bucket.windows) {
74
+ if (!item || typeof item !== 'object' || Array.isArray(item)) continue;
75
+ const baseWindow = usageWindowLabel(item.windowSeconds);
76
+ const remainingPercent = clampPercent(item.remainingPercent);
77
+ const resetAt = isoFromUnixSeconds(item.resetAt);
78
+ if (!baseWindow || seenInBucket.has(baseWindow) || remainingPercent === undefined) continue;
79
+ seenInBucket.add(baseWindow);
80
+ const window = bucketIndex === 0 || !bucketName ? baseWindow : `${bucketName} · ${baseWindow}`;
81
+ windows.push({ window, remainingPercent, ...(resetAt ? { resetAt } : {}) });
82
+ }
83
+ }
84
+ const individual = usage.individualLimit;
85
+ let individualLimit;
86
+ if (individual && typeof individual === 'object' && !Array.isArray(individual)) {
87
+ const limit = finiteNumber(individual.limit);
88
+ const used = finiteNumber(individual.used);
89
+ const remaining = finiteNumber(individual.remaining);
90
+ const remainingPercent = clampPercent(individual.remainingPercent ?? (limit > 0 && remaining !== undefined ? remaining / limit * 100 : undefined));
91
+ if (limit !== undefined && used !== undefined && remaining !== undefined && limit > 0 && remainingPercent !== undefined) {
92
+ individualLimit = {
93
+ limit: String(individual.limit),
94
+ used: String(individual.used),
95
+ remaining: String(individual.remaining),
96
+ remainingPercent,
97
+ };
98
+ }
99
+ }
100
+ const credits = usage.credits;
101
+ let codexCredits;
102
+ if (credits && typeof credits === 'object' && !Array.isArray(credits) && typeof credits.unlimited === 'boolean') {
103
+ if (credits.unlimited) {
104
+ codexCredits = { unlimited: true };
105
+ } else if (typeof credits.balance === 'string' && credits.balance.trim() !== '') {
106
+ codexCredits = { unlimited: false, balance: credits.balance };
107
+ } else if (finiteNumber(credits.balance) !== undefined) {
108
+ codexCredits = { unlimited: false, balance: String(credits.balance) };
109
+ } else {
110
+ // balance 是可选字段,但 unlimited=false 仍是一个有效、可展示的 Credits 状态。
111
+ codexCredits = { unlimited: false };
112
+ }
113
+ }
114
+ if (windows.length === 0 && individualLimit === undefined && codexCredits === undefined) throw new Error('codex usage has no usable allowance');
115
+ return {
116
+ windows,
117
+ ...(individualLimit ? { individualLimit } : {}),
118
+ ...(codexCredits ? { credits: codexCredits } : {}),
119
+ };
120
+ }
121
+
122
+ /** OpenCode Go usage payload → 剩余百分比窗口;无效窗口单独跳过,限流窗口保留。 */
123
+ export function normalizeOpenCodeUsage(payload) {
124
+ const usage = payload && typeof payload === 'object' && !Array.isArray(payload) ? (payload.usage ?? payload) : undefined;
125
+ if (!usage || typeof usage !== 'object' || Array.isArray(usage)) throw new Error('invalid opencode usage');
126
+ const windows = [];
127
+ for (const [key, label] of [['rolling', '5h'], ['weekly', 'weekly'], ['monthly', 'monthly']]) {
128
+ const detail = usage[key];
129
+ if (!detail || typeof detail !== 'object' || Array.isArray(detail)) continue;
130
+ const status = detail.status;
131
+ if (status !== undefined && status !== null && status !== 'ok' && status !== 'rate-limited') continue;
132
+ const usedPercent = clampPercent(detail.percent);
133
+ if (usedPercent === undefined) continue;
134
+ // percent=0 时 OpenCode 返回的是 now+window 占位值,不是可展示的 resetAt。
135
+ const resetAt = usedPercent === 0 ? undefined : isoFromDate(detail.resetsAt);
136
+ windows.push({
137
+ window: label,
138
+ remainingPercent: 100 - usedPercent,
139
+ ...(status === 'rate-limited' ? { limited: true } : {}),
140
+ ...(resetAt ? { resetAt } : {}),
141
+ });
142
+ }
143
+ if (windows.length === 0) throw new Error('opencode usage has no usable windows');
144
+ return { windows };
145
+ }