@dsh-mobile/mobile-remote 3.2.6 → 3.3.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 (64) hide show
  1. package/FAQ.md +19 -12
  2. package/README.md +39 -40
  3. package/cordis.patch.yml +8 -4
  4. package/docs/PRIVACY-POLICY.en.md +88 -61
  5. package/docs/PRIVACY-POLICY.md +88 -61
  6. package/docs/SUPPORT.md +5 -5
  7. package/docs/TERMS-OF-SERVICE.en.md +1 -1
  8. package/docs/TERMS-OF-SERVICE.md +1 -1
  9. package/docs/USER-GUIDE.zh-CN.md +562 -0
  10. package/lib/account-usage-query.js +117 -4
  11. package/lib/assistant-prefs.js +147 -0
  12. package/lib/auto-config.js +55 -3
  13. package/lib/backup.js +405 -0
  14. package/lib/break-reminder.js +133 -0
  15. package/lib/client.js +57 -11
  16. package/lib/config.js +94 -5
  17. package/lib/git-read-bundled-provider.js +12 -3
  18. package/lib/git-read-service.js +4 -0
  19. package/lib/host-compat.js +25 -0
  20. package/lib/http-util.js +6 -2
  21. package/lib/index.js +987 -74
  22. package/lib/memory/context.js +76 -0
  23. package/lib/memory/decay.js +144 -0
  24. package/lib/memory/extract.js +146 -0
  25. package/lib/memory/routes.js +198 -0
  26. package/lib/memory/store.js +667 -0
  27. package/lib/notify-copy.js +245 -0
  28. package/lib/permission-guide.js +184 -0
  29. package/lib/persona-cards.js +362 -0
  30. package/lib/proactive-material.js +162 -0
  31. package/lib/proactive.js +369 -0
  32. package/lib/protected-paths.js +130 -0
  33. package/lib/protocol.js +35 -0
  34. package/lib/rate-limit.js +1 -1
  35. package/lib/relay/connector.js +97 -12
  36. package/lib/relay/devices.js +14 -0
  37. package/lib/relay/fingerprint.js +55 -0
  38. package/lib/relay/identity.js +69 -0
  39. package/lib/relay/on-demand.js +84 -0
  40. package/lib/relay/phone.js +87 -12
  41. package/lib/reminders.js +140 -0
  42. package/lib/rpc-adapter.js +21 -2
  43. package/lib/session-rotation.js +198 -0
  44. package/lib/timeline.js +1 -1
  45. package/package.json +31 -14
  46. package/CHANGELOG.md +0 -1336
  47. package/CONTRIBUTING.md +0 -61
  48. package/docs/00-/345/274/200/345/217/221/346/200/273/347/272/262.md +0 -432
  49. package/docs/01-PRD.md +0 -148
  50. package/docs/02-architecture.md +0 -249
  51. package/docs/03-api.md +0 -882
  52. package/docs/04-security.md +0 -110
  53. package/docs/05-test-cases.md +0 -376
  54. package/docs/06-install-run.md +0 -349
  55. package/docs/07-user-manual.md +0 -92
  56. package/docs/08-/346/211/251/345/261/225/345/274/200/345/217/221/346/214/207/345/215/227.md +0 -86
  57. package/docs/09-compatibility.md +0 -201
  58. package/docs/11-remote-relay-guide.md +0 -85
  59. package/docs/APP-ENCRYPTION-DESCRIPTION.md +0 -50
  60. package/docs/APP-ENCRYPTION-DESCRIPTION.pdf +0 -0
  61. package/docs/APP-REVIEW-NOTES.md +0 -135
  62. package/docs/BRAND-ASSETS.md +0 -142
  63. package/docs/STORE-LAUNCH.md +0 -305
  64. package/docs/STORE-LISTING.md +0 -150
@@ -11,6 +11,39 @@ import { normalizeCodexUsage, normalizeDeepSeekBalance, normalizeOpenCodeUsage }
11
11
  import { safeFailureReason } from "./api-helpers.js";
12
12
  import { readSettingsSection, readSettingsSectionStrict } from "./host-compat.js";
13
13
 
14
+ /** 插件自身版本:作为 DSH 账号请求的客户端版本头(读不到时退回 unknown)。 */
15
+ const pluginVersion = (() => {
16
+ try {
17
+ return createRequire(import.meta.url)("../package.json").version ?? "unknown";
18
+ } catch {
19
+ return "unknown";
20
+ }
21
+ })();
22
+
23
+ /** DSH 账号服务默认的客户端身份;手机端可覆盖语言与时区。 */
24
+ function accountClientMetadata(client = {}) {
25
+ return {
26
+ version: typeof client.version === "string" && client.version !== "" ? client.version : pluginVersion,
27
+ locale: typeof client.locale === "string" && client.locale !== "" ? client.locale : "zh-CN",
28
+ timezoneOffsetSeconds: Number.isFinite(client.timezoneOffsetSeconds)
29
+ ? client.timezoneOffsetSeconds
30
+ : -new Date().getTimezoneOffset() * 60,
31
+ };
32
+ }
33
+
34
+ /** DSH 内置的 DeepSeek 账号服务;旧版宿主没有该能力时返回 undefined。 */
35
+ function deepSeekAccountService(ctx) {
36
+ try {
37
+ const service = ctx?.get?.("deepseekAccount");
38
+ return service && typeof service.getBalance === "function" ? service : undefined;
39
+ } catch {
40
+ return undefined;
41
+ }
42
+ }
43
+
44
+ /** 充值入口:账号服务给了部署地址就用它,否则用官方平台地址。 */
45
+ const DEFAULT_DEEPSEEK_TOP_UP = "https://platform.deepseek.com/top_up";
46
+
14
47
  /** 与 PC 端设置页一致的凭据引用派生规则(v2.6):路由 id 大写 → `<ID>_API_KEY`。 */
15
48
  export function deriveKeyRef(provider) {
16
49
  return `${String(provider).toUpperCase().replace(/[^A-Z0-9]+/g, "_")}_API_KEY`;
@@ -74,9 +107,88 @@ async function loadCodexConnect() {
74
107
  throw bareError;
75
108
  }
76
109
 
77
- async function queryDeepSeekUsage(ctx) {
110
+ /**
111
+ * 读取 DSH 登录的 DeepSeek 账号余额。
112
+ *
113
+ * 很多人是在 DSH 里用 DeepSeek 账号登录(`deepseekAccount` 服务持有登录凭证),
114
+ * 而不是在「设置 → 模型」里填 API Key;只查 DEEPSEEK_API_KEY 会让他们整块余额消失。
115
+ * 返回值区分三态:`ready` / `signed-out` / `failed`,`unavailable` 表示宿主没有账号能力。
116
+ */
117
+ export async function queryDeepSeekAccountBalance(ctx, client = {}) {
118
+ const service = deepSeekAccountService(ctx);
119
+ if (!service) return { status: "unavailable" };
120
+ const metadata = accountClientMetadata(client);
121
+ let links;
122
+ try {
123
+ const state = await service.getState?.();
124
+ links = state?.links;
125
+ // getState 不可用时仍尝试 getBalance:它自己会在未登录时返回 null。
126
+ if (state && state.status !== "credential-stored") return { status: "signed-out", links };
127
+ } catch {
128
+ // 账号状态读失败不等于未登录:继续走余额查询,由它给出真实结果。
129
+ }
130
+ let balance;
131
+ try {
132
+ balance = await service.getBalance(metadata);
133
+ } catch (err) {
134
+ return { status: "failed", failedReason: safeFailureReason(err), links };
135
+ }
136
+ if (balance === null) return { status: "signed-out", links };
137
+ if (balance?.status !== "ready") return { status: "failed", failedReason: "账号余额查询失败", links };
138
+ let profile;
139
+ try {
140
+ const result = await service.getProfile?.(metadata);
141
+ if (result?.status === "ready") profile = result.value;
142
+ } catch {
143
+ // 账号标签是可选的展示信息,读失败不影响余额。
144
+ }
145
+ return {
146
+ status: "ready",
147
+ wallets: Array.isArray(balance.value) ? balance.value : [],
148
+ bonusWallets: Array.isArray(balance.bonusWallets) ? balance.bonusWallets : [],
149
+ profile,
150
+ links,
151
+ };
152
+ }
153
+
154
+ /** CNY 优先;没有 CNY 时用第一个钱包(与 API Key 余额的取值规则一致)。 */
155
+ function preferredWallet(wallets) {
156
+ return wallets.find((wallet) => wallet?.currency === "CNY") ?? wallets[0];
157
+ }
158
+
159
+ async function queryDeepSeekUsage(ctx, client = {}) {
160
+ const account = await queryDeepSeekAccountBalance(ctx, client);
161
+ const topUpUrl = account.links?.topUpUrl ?? DEFAULT_DEEPSEEK_TOP_UP;
162
+ if (account.status === "ready") {
163
+ const wallet = preferredWallet(account.wallets);
164
+ const bonus = preferredWallet(account.bonusWallets);
165
+ return {
166
+ configured: true,
167
+ source: {
168
+ id: "deepseek",
169
+ title: "DeepSeek",
170
+ kind: "balance",
171
+ ...(wallet ? { amount: wallet.balance, currency: wallet.currency } : {}),
172
+ ...(bonus ? { bonus: { amount: bonus.balance, currency: bonus.currency } } : {}),
173
+ available: true,
174
+ topUpUrl,
175
+ ...(account.profile && (account.profile.name || account.profile.contact) ? {
176
+ account: {
177
+ ...(typeof account.profile.name === "string" && account.profile.name !== "" ? { displayName: account.profile.name } : {}),
178
+ ...(typeof account.profile.contact === "string" && account.profile.contact !== "" ? { maskedEmail: account.profile.contact } : {}),
179
+ },
180
+ } : {}),
181
+ },
182
+ };
183
+ }
78
184
  const key = await resolveCredentialValue(ctx, "DEEPSEEK_API_KEY");
79
- if (!key) return { configured: false };
185
+ if (!key) {
186
+ // 账号已登录但余额查询失败:把失败原因报上去,而不是退回"未配置"。
187
+ if (account.status === "failed") {
188
+ return { configured: true, failed: true, failedId: "deepseek", failedReason: account.failedReason };
189
+ }
190
+ return { configured: false };
191
+ }
80
192
  try {
81
193
  const response = await fetch("https://api.deepseek.com/user/balance", {
82
194
  headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
@@ -95,6 +207,7 @@ async function queryDeepSeekUsage(ctx) {
95
207
  title: "DeepSeek",
96
208
  kind: "balance",
97
209
  ...balance,
210
+ topUpUrl,
98
211
  },
99
212
  };
100
213
  } catch (err) {
@@ -251,9 +364,9 @@ async function queryOpenCodeUsage(ctx) {
251
364
  }
252
365
  }
253
366
 
254
- export async function queryAccountUsage(ctx) {
367
+ export async function queryAccountUsage(ctx, client = {}) {
255
368
  const results = await Promise.all([
256
- queryDeepSeekUsage(ctx),
369
+ queryDeepSeekUsage(ctx, client),
257
370
  queryCodexUsage(ctx),
258
371
  queryOpenCodeUsage(ctx),
259
372
  ]);
@@ -0,0 +1,147 @@
1
+ /**
2
+ * 助手偏好(模式 / 人格)的读写接口(T9)。
3
+ *
4
+ * 为什么要这个接口:模式与人格必须**同时**作用在两个地方——
5
+ * 1. 推送与通知的措辞(服务端已有);
6
+ * 2. agent 对话时的上下文(人格决定语气、模式决定能看到哪些记忆)。
7
+ * 之前 App 里切换只写进了手机本地,服务端一直是默认值,于是「切成生活模式」
8
+ * 只改了手机上一句提示,电脑上的助手仍然拿着工作记忆在说话。这不是没做,
9
+ * 是做了但没生效。
10
+ *
11
+ * 落盘策略:写进 `<状态目录>/assistant.json`,重启后保持。之所以不写回
12
+ * `cordis.patch.yml`:那是用户手写的部署配置,插件不该去改它。
13
+ */
14
+ import { readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
15
+ import { join } from "node:path";
16
+ import { parseHm } from "./notify-copy.js";
17
+
18
+ const MODES = ["work", "life"];
19
+ /** Persona card ids (T-31): same rule as lib/persona-cards.js validatePersonaCard. */
20
+ const PERSONA_CARD_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
21
+ const PERSONAS = ["colleague", "character"];
22
+
23
+ /**
24
+ * 安静时段的合法性判断。返回 `true` 表示两个时间点都能解析。
25
+ *
26
+ * 故意不接受「猜一个默认值」:配置写错时宁可多吵一次,
27
+ * 也不要把用户的通知整段吞掉(见 config.js 里同一条注释)。
28
+ */
29
+ function validWindow(start, end) {
30
+ return parseHm(start) !== null && parseHm(end) !== null;
31
+ }
32
+
33
+ /**
34
+ * @param {object} options
35
+ * @param {string} options.dir 状态目录(与 auth-token、记忆库同层)
36
+ * @param {() => {mode: string, persona: string, quietHours?: {start: string, end: string}}} options.defaults 配置里的默认值
37
+ */
38
+ export function createAssistantPrefs({ dir, defaults }) {
39
+ const file = join(dir, "assistant.json");
40
+ let cached = null;
41
+
42
+ function load() {
43
+ if (cached) return cached;
44
+ const fallback = defaults();
45
+ try {
46
+ const raw = JSON.parse(readFileSync(file, "utf8"));
47
+ // 安静时段单独校验:文件里可能是旧版本写的、也可能是手改坏的。
48
+ // 只有两个端点都合法才采用,否则整体回落到配置值——半个窗口比没有更糟。
49
+ const quiet = raw?.quietHours;
50
+ const quietOk =
51
+ quiet && validWindow(quiet.start, quiet.end)
52
+ ? { start: quiet.start, end: quiet.end }
53
+ : fallback.quietHours;
54
+ cached = {
55
+ mode: MODES.includes(raw?.mode) ? raw.mode : fallback.mode,
56
+ persona: PERSONAS.includes(raw?.persona) ? raw.persona : fallback.persona,
57
+ quietHours: quietOk
58
+ ? { start: quietOk.start, end: quietOk.end }
59
+ : { start: "23:30", end: "08:30" },
60
+ // T-15: the user's own off switch for the break reminder (on unless they turned it off).
61
+ breakReminder: typeof raw?.breakReminder === "boolean" ? raw.breakReminder : true,
62
+ // T-31: the active persona card (an id). Absent = the old colleague/character switch decides.
63
+ ...(PERSONA_CARD_ID.test(raw?.personaCard ?? "") ? { personaCard: raw.personaCard } : {}),
64
+ };
65
+ } catch {
66
+ // 文件不存在或损坏:回到配置默认值,不因为一个坏文件让助手不可用。
67
+ cached = {
68
+ mode: fallback.mode,
69
+ persona: fallback.persona,
70
+ quietHours: fallback.quietHours ?? { start: "23:30", end: "08:30" },
71
+ breakReminder: true,
72
+ };
73
+ }
74
+ return cached;
75
+ }
76
+
77
+ function save(next) {
78
+ mkdirSync(dir, { recursive: true });
79
+ // 原子写:先写临时文件再 rename,避免断电/崩溃留下半个 JSON。
80
+ const tmp = `${file}.tmp`;
81
+ writeFileSync(tmp, JSON.stringify(next, null, 2), "utf8");
82
+ renameSync(tmp, file);
83
+ cached = next;
84
+ }
85
+
86
+ return {
87
+ file,
88
+ /** 当前有效的模式与人格。 */
89
+ get: () => ({ ...load() }),
90
+
91
+ /**
92
+ * 改一项或两项。非法值直接拒绝,不「猜一个最近的」:
93
+ * 猜错会让用户以为切换成功,实际还在原来的模式里。
94
+ */
95
+ set(patch) {
96
+ const cur = load();
97
+ const next = { ...cur };
98
+ if (patch?.mode !== undefined) {
99
+ if (!MODES.includes(patch.mode)) {
100
+ throw new Error(`mode 必须是 ${MODES.join(" / ")}`);
101
+ }
102
+ next.mode = patch.mode;
103
+ }
104
+ if (patch?.persona !== undefined) {
105
+ if (!PERSONAS.includes(patch.persona)) {
106
+ throw new Error(`persona 必须是 ${PERSONAS.join(" / ")}`);
107
+ }
108
+ next.persona = patch.persona;
109
+ }
110
+ if (patch?.quietHours !== undefined) {
111
+ const start = patch.quietHours?.start;
112
+ const end = patch.quietHours?.end;
113
+ if (!validWindow(start, end)) {
114
+ // 不静默保留旧值:用户会以为自己改成功了,夜里照样被吵醒。
115
+ throw new Error("quietHours 必须是 {start: \"HH:MM\", end: \"HH:MM\"}");
116
+ }
117
+ next.quietHours = { start, end };
118
+ }
119
+ if (patch?.personaCard !== undefined) {
120
+ if (typeof patch.personaCard !== "string" || !PERSONA_CARD_ID.test(patch.personaCard)) {
121
+ throw new Error("personaCard 必须是人格卡的 id / personaCard must be a persona card id");
122
+ }
123
+ next.personaCard = patch.personaCard;
124
+ }
125
+ if (patch?.breakReminder !== undefined) {
126
+ if (typeof patch.breakReminder !== "boolean") throw new Error("breakReminder 必须是 true / false");
127
+ next.breakReminder = patch.breakReminder;
128
+ }
129
+ save(next);
130
+ return { ...next };
131
+ },
132
+ };
133
+ }
134
+
135
+ // personaBrief was removed with T-31 (D8): the active persona card's own text is the only
136
+ // persona text the model sees (lib/persona-cards.js, personaPromptText).
137
+
138
+ /** 模式 → 一段给模型看的说明。生活模式明确要求不提工作内容。 */
139
+ export function modeBrief(mode) {
140
+ if (mode === "life") {
141
+ return [
142
+ "当前是生活模式:不主动提项目、客户、报错、未发布的功能。",
143
+ "记忆里工作范围的内容这一轮看不到,也不要凭印象补出来。",
144
+ ].join("\n");
145
+ }
146
+ return "当前是工作模式:可以使用项目与长期记忆,回答以可执行、可核对为准。";
147
+ }
@@ -8,7 +8,8 @@
8
8
  * - `lanBridge.enabled: "auto"` 仅在需要时开桥(桌面版 webserver 只听回环)。
9
9
  * - `formatConnectionBanner` 启动时把手机 App 需要填的两项(地址 + 口令)打印出来。
10
10
  *
11
- * 向后兼容:`authToken` 为空仍然表示「关闭认证」、`lanBridge.enabled` 仍可写 true/false;
11
+ * 向后兼容:`authToken` 为空仅在服务只有本机可达时表示「关闭认证」,否则按 `@auto` 处理(T-03,见
12
+ * `effectiveAuthSetting`);`lanBridge.enabled` 仍可写 true/false;
12
13
  * 这些「自动」值只会出现在插件自带的 `cordis.patch.yml` 里,已有手写配置的用户行为不变。
13
14
  */
14
15
  import { randomBytes } from "node:crypto";
@@ -32,7 +33,7 @@ export function mobileRemoteStateDir(env = process.env, home = homedir()) {
32
33
 
33
34
  /**
34
35
  * 解析 `authToken`。
35
- * - 不是 `@auto`:原样返回(空串 = 关闭认证,保持旧语义)。
36
+ * - 不是 `@auto`:原样返回(空串 = 关闭认证;调用方只在服务仅本机可达时才会传空串,见 effectiveAuthSetting)。
36
37
  * - `@auto`:读 `<stateDir>/auth-token`;没有或损坏就生成新的并原子写入(0600)。
37
38
  * 写盘失败不阻断启动:本次进程内用内存口令,但会返回 `persistError`,调用方应提示
38
39
  * 「重启后口令会变,手机需要重新配对」。
@@ -60,6 +61,49 @@ export function resolveAuthToken(configured, { dir = mobileRemoteStateDir(), gen
60
61
  }
61
62
  }
62
63
 
64
+ /**
65
+ * T-03 (finding E6): whether nothing but this computer can reach the mobile API.
66
+ *
67
+ * True only when the DSH webserver listens on a loopback address and none of the ways out
68
+ * is on: no LAN bridge, no `trustedHosts` (a tunnel or reverse proxy), no relay (it replays
69
+ * phone requests into this server). An unknown webserver host counts as reachable, so the
70
+ * answer fails closed.
71
+ */
72
+ export function isLoopbackOnly({ webHost, lanBridgeEnabled = false, trustedHosts = [], relayEnabled = false } = {}) {
73
+ if (typeof webHost !== "string" || !LOOPBACK_HOSTS.has(webHost.trim().toLowerCase())) return false;
74
+ if (lanBridgeEnabled || relayEnabled) return false;
75
+ return !(Array.isArray(trustedHosts) && trustedHosts.length > 0);
76
+ }
77
+
78
+ /**
79
+ * T-03 (finding E6): the `authToken` setting to resolve.
80
+ *
81
+ * An empty token used to switch authentication off wherever the server was reachable, so a
82
+ * user config that replaced the shipped `"@auto"` and left the token out opened an agent with
83
+ * shell access to the whole LAN. Now an empty (or missing) token means "off" only when the
84
+ * server is loopback-only (`isLoopbackOnly`); everywhere else it is treated as `"@auto"`.
85
+ * A non-empty value is returned unchanged.
86
+ */
87
+ export function effectiveAuthSetting(configured, reach = {}) {
88
+ if (typeof configured === "string" && configured !== "") return configured;
89
+ return isLoopbackOnly(reach) ? "" : AUTO;
90
+ }
91
+
92
+ /**
93
+ * Replace an auto-managed token with a fresh one (T-62: after a device is revoked). Written
94
+ * atomically over `<dir>/auth-token` (0600). Only for `@auto` tokens: a token the owner wrote
95
+ * into their config is theirs to change. Throws when the file cannot be written.
96
+ */
97
+ export function rotateAuthToken({ dir = mobileRemoteStateDir(), generate = () => randomBytes(24).toString("base64url") } = {}) {
98
+ const file = join(dir, "auth-token");
99
+ const token = generate();
100
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
101
+ const tmp = `${file}.${process.pid}.tmp`;
102
+ writeFileSync(tmp, `${token}\n`, { mode: 0o600 });
103
+ renameSync(tmp, file);
104
+ return { token, file };
105
+ }
106
+
63
107
  /**
64
108
  * 解析 `lanBridge.enabled`:true/false 原样;`"auto"` = 需要才开。
65
109
  * 「需要」= webserver 只听回环(桌面版强制如此,手机直连不了)。web 版 webserver 已经听 0.0.0.0,
@@ -85,13 +129,21 @@ export function resolveLanBridgePort(setting, port, webPort) {
85
129
  * 启动时打印给人看的「手机 App 要填的两项」。
86
130
  * 口令只在**自动生成**时打印——那是用户唯一能第一时间拿到它的地方;用户自己写进配置的口令不进日志。
87
131
  */
88
- export function formatConnectionBanner({ addresses, token, tokenIsAuto, tokenFile, persistError, authEnabled = true }) {
132
+ /**
133
+ * T-62 (E11): an auto token is printed only on the start that generated it (`tokenNew`). Later
134
+ * starts say where it is saved instead: stderr often ends up in log files.
135
+ */
136
+ export function formatConnectionBanner({ addresses, token, tokenIsAuto, tokenNew = true, tokenFile, persistError, authEnabled = true }) {
89
137
  const [first, ...rest] = addresses;
90
138
  const lines = ["mobile-remote ▶ 手机 App 连接信息 / Phone app connection"];
91
139
  lines.push(` 电脑地址 Address : ${first}`);
92
140
  for (const extra of rest) lines.push(` ${extra} (备用 alternative)`);
93
141
  if (!authEnabled) {
94
142
  lines.push(" 访问口令 Token : (未启用认证 / authentication is OFF)");
143
+ } else if (tokenIsAuto && !tokenNew) {
144
+ lines.push(
145
+ ` 访问口令 Token : (已保存在 ${tokenFile ?? "状态目录"};也可在 DSH 设置页「连接移动端设备」查看 / saved in ${tokenFile ?? "the state folder"}; also shown in DSH settings)`,
146
+ );
95
147
  } else if (tokenIsAuto) {
96
148
  lines.push(` 访问口令 Token : ${token}`);
97
149
  if (persistError) {