@dsh-mobile/mobile-remote 3.3.1 → 3.4.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 (58) hide show
  1. package/README.md +9 -5
  2. package/docs/PRIVACY-POLICY.en.md +10 -3
  3. package/docs/PRIVACY-POLICY.md +10 -3
  4. package/docs/USER-GUIDE.zh-CN.md +1 -0
  5. package/lib/account-usage-query.js +60 -60
  6. package/lib/account-usage.js +10 -10
  7. package/lib/api-helpers.js +109 -109
  8. package/lib/assistant-prefs.js +82 -59
  9. package/lib/auto-config.js +65 -65
  10. package/lib/backup.js +117 -117
  11. package/lib/break-reminder.js +45 -45
  12. package/lib/client.js +93 -93
  13. package/lib/config.js +232 -218
  14. package/lib/git-read-bundled-provider.js +12 -12
  15. package/lib/git-read-service.js +5 -5
  16. package/lib/host-compat.js +84 -84
  17. package/lib/http-util.js +17 -17
  18. package/lib/index.js +1534 -1534
  19. package/lib/memory/context.js +44 -44
  20. package/lib/memory/decay.js +93 -93
  21. package/lib/memory/extract.js +77 -77
  22. package/lib/memory/routes.js +33 -33
  23. package/lib/memory/store.js +196 -196
  24. package/lib/notify-copy.js +93 -93
  25. package/lib/permission-guide.js +86 -86
  26. package/lib/persona-cards.js +73 -65
  27. package/lib/phone-action-args.js +175 -0
  28. package/lib/phone-actions.js +227 -0
  29. package/lib/phone-announce.js +58 -0
  30. package/lib/proactive-material.js +42 -42
  31. package/lib/proactive.js +121 -121
  32. package/lib/protected-paths.js +79 -79
  33. package/lib/protocol.js +61 -26
  34. package/lib/push.js +29 -29
  35. package/lib/rate-limit.js +16 -16
  36. package/lib/relay/connector.js +246 -102
  37. package/lib/relay/crypto.js +15 -15
  38. package/lib/relay/devices.js +36 -36
  39. package/lib/relay/fingerprint.js +34 -34
  40. package/lib/relay/identity.js +26 -26
  41. package/lib/relay/mux.js +60 -46
  42. package/lib/relay/noise.js +40 -40
  43. package/lib/relay/on-demand.js +33 -33
  44. package/lib/relay/p2p.js +239 -0
  45. package/lib/relay/pairing.js +24 -24
  46. package/lib/relay/phone.js +62 -40
  47. package/lib/relay/serve.js +21 -21
  48. package/lib/relay/signal.js +69 -0
  49. package/lib/relay/ws-server.js +32 -32
  50. package/lib/reminders.js +15 -15
  51. package/lib/rpc-adapter.js +43 -43
  52. package/lib/session-list.js +31 -31
  53. package/lib/session-rotation.js +95 -95
  54. package/lib/session-title-cache.js +35 -35
  55. package/lib/session-title-refresh.js +51 -51
  56. package/lib/timeline.js +140 -140
  57. package/lib/turn-outline.js +104 -104
  58. package/package.json +6 -13
@@ -1,16 +1,16 @@
1
- /**
2
- * HTTP/文本层的纯辅助:路径脱敏、请求头读取、截断、MIME、二维码地址排序、发送回执 TTL、服务端路径归一、问答校验、抓取失败归类。
3
- * 从 lib/index.js 原样拆出(行为不变)。
4
- */
1
+
2
+
3
+
4
+
5
5
  import { extname } from "node:path";
6
6
 
7
- /** 主机绝对路径脱敏(v3.1.5 S7):抹掉 POSIX 多段路径与 Windows 盘符路径。
8
- * 宿主错误 message 常带工作区/会话/设置文件路径。此前只在服务端日志与推送里用过,
9
- * 结果 `/files`、`/directories`、`rpcError` 等把主机绝对路径原样回给了客户端——
10
- * 现在日志、HTTP 错误详情、推送正文统一走这里(原文只进服务端日志)。
11
- * 刻意保留单段 `/foo`(如 URL 的路径段不会被整段吞掉)。 */
7
+
8
+
9
+
10
+
11
+
12
12
  const REDACT_PATH_PATTERN = /(?:\/[\p{L}\p{N}\p{M}_.~@+-]+){2,}|[A-Za-z]:\\[^\s"']*/gu;
13
- /** A-45: a quoted absolute path (how Node's fs errors print it) is removed whole, spaces and all. */
13
+
14
14
  const REDACT_QUOTED_PATH = /(['"`])(?:\/|[A-Za-z]:\\)[^'"`\n]*\1/g;
15
15
 
16
16
  export function redactPathText(value) {
@@ -19,26 +19,26 @@ export function redactPathText(value) {
19
19
  .replace(REDACT_PATH_PATTERN, "<redacted>");
20
20
  }
21
21
 
22
- /**
23
- * 普通文件下载能力:Range / HEAD / ETag(v3.2.3)。
24
- *
25
- * App 用它决定能不能"只取前 256 KiB 预览"和"大文件断点续传";不存在该能力位时
26
- * 自动退回整文件 GET(旧插件行为)。
27
- */
22
+
23
+
24
+
25
+
26
+
27
+
28
28
  export const FILE_RANGE_CAPABILITIES = {
29
29
  version: 1,
30
30
  supported: true,
31
31
  };
32
32
 
33
- /** 读请求头单值文本(防御数组/非字符串)。 */
33
+
34
34
  export function requestHeaderText(req, name) {
35
35
  const raw = req?.headers?.[name];
36
36
  const value = Array.isArray(raw) ? raw[0] : raw;
37
37
  return typeof value === "string" ? value : "";
38
38
  }
39
39
 
40
- /** 截断字符串到上限(超出加省略号),避免移动端流量/渲染膨胀。
41
- * P2:截断提示本身计入上限——输出总长严格 ≤ max(对齐文档的"≤ N 字符"语义)。 */
40
+
41
+
42
42
  export function clampText(text, max) {
43
43
  text = text === undefined || text === null ? "" : String(text);
44
44
  if (text.length <= max) return text;
@@ -47,7 +47,7 @@ export function clampText(text, max) {
47
47
  return keep > 0 ? `${text.slice(0, keep)}${suffix}` : text.slice(0, max);
48
48
  }
49
49
 
50
- /** v3.1.2:文件下载 MIME(扩展名映射,兜底 octet-stream)。 */
50
+
51
51
  const FILE_MIME = {
52
52
  ".txt": "text/plain; charset=utf-8", ".md": "text/markdown; charset=utf-8", ".json": "application/json",
53
53
  ".pdf": "application/pdf", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
@@ -61,11 +61,11 @@ const FILE_MIME = {
61
61
 
62
62
  export const fileMimeOf = (name) => FILE_MIME[extname(name).toLowerCase()] ?? "application/octet-stream";
63
63
 
64
- /**
65
- * 有界并发映射(保持入参顺序)。用于**不能**一次性扇出的上游读取:
66
- * 逐个 `readTitleSnapshot` 在真实宿主上每次都会自带一轮全语料枚举,
67
- * `Promise.all(ids)` 会让 N 个枚举同时开跑。
68
- */
64
+
65
+
66
+
67
+
68
+
69
69
  export const mapBounded = async (items, width, worker) => {
70
70
  const list = [...items];
71
71
  if (list.length === 0) return [];
@@ -79,34 +79,34 @@ export const mapBounded = async (items, width, worker) => {
79
79
  results[index] = await worker(list[index], index);
80
80
  }
81
81
  };
82
- // 评审 note 908:不能用 `Promise.all`——它**首拒即返回**,调用方(以及它背后的折叠串行门)
83
- // 会在其余 worker 仍在清理时就被释放;重试随即再开一路,旧 3 路 + 新 4 路叠加实测
84
- // maxActive=7,突破 ≤4 的读取宽度上限。改为等**全部** worker settle 之后再重抛原失败,
85
- // 使"在途读取"真正受调用方生命周期约束。
82
+
83
+
84
+
85
+
86
86
  const settled = await Promise.allSettled(Array.from({ length: Math.min(width, list.length) }, run));
87
87
  const failed = settled.find((entry) => entry.status === "rejected");
88
88
  if (failed) throw failed.reason;
89
89
  return results;
90
90
  };
91
91
 
92
- // ── 宿主 API 代际探测(ADR 0017)────────────────────────────────────────────
93
- // 宿主不为 API 声明契约版本,插件只能按**结构特征**探测当前是哪一代,而不是查版本号。
94
- // 下列四处差异都在宿主 0.2.0 一并发生;各自用最贴近该处差异的结构特征判别,
95
- // 是为了避免"用一个特征的版本号去推断另一个特征"这种脆弱做法。
96
- // 判别必须是"服务存在但语义不同"也能识别的——这正是能力语义漂移的形态。
97
-
98
- /**
99
- * 二维码地址排序(issue #49)。
100
- *
101
- * 默认保持「局域网私有地址优先」:在家扫码必须给手机可达的局域网地址,组网地址
102
- * (Tailscale CGNAT 100.64/10)排在其后,避免「桌面有 Tailscale、手机没登录 → 扫到黑洞」。
103
- *
104
- * 例外:**当前没有任何局域网私有地址**时,把 Tailscale 提到最前。这类机器(校园网 / 热点 /
105
- * 只剩虚拟网卡)若不这样排,唯一可用的组网地址会被「其他」段压到后面,二维码首选变成不可达地址。
106
- * 两种情形都按「手机能否直接到达」取最优,而不是按网卡枚举顺序。
107
- *
108
- * 排序:0 = 10./192.168.x;1 = 172.16-31;2 = 100.64/10;3 = 其他。
109
- */
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+
110
110
  export const orderQrAddresses = (ips) => {
111
111
  const rankOf = (ip) => {
112
112
  const o = String(ip).split(".").map(Number);
@@ -120,18 +120,18 @@ export const orderQrAddresses = (ips) => {
120
120
  const rank = rankOf(ip);
121
121
  return rank === 0 || rank === 1;
122
122
  });
123
- // 没有局域网私有地址时,把 CGNAT 从 2 提到 0(其余保持原相对次序)
123
+
124
124
  const adjusted = (ip) => (rankOf(ip) === 2 && !hasLanPrivate ? 0 : rankOf(ip));
125
125
  return [...ips].sort((a, b) => adjusted(a) - adjusted(b));
126
126
  };
127
127
 
128
- /** v3.0.0(热修 07):回执过期判定(顶层纯函数,便于单测)——now 超过 at+ttl 即过期。 */
128
+
129
129
  export function receiptExpired(at, now, ttl = 15 * 60 * 1000) {
130
130
  return now - at > ttl;
131
131
  }
132
132
 
133
- /** v3.0.0(热修 08):回执**全量**过期/上限清理(顶层纯函数,可单测)——返回是否有删除。
134
- * 语义对齐 receiptExpired:恰好 TTL 边界不算过期,仅超过才算;超上限按最旧淘汰。 */
133
+
134
+
135
135
  export function pruneReceiptMap(receipts, now = Date.now(), ttl = 15 * 60 * 1000, max = 2000) {
136
136
  let changed = false;
137
137
  for (const [k, v] of receipts) {
@@ -141,27 +141,27 @@ export function pruneReceiptMap(receipts, now = Date.now(), ttl = 15 * 60 * 1000
141
141
  return changed;
142
142
  }
143
143
 
144
- /** v3.1.1(issue #5):把客户端传来的路径按目标平台归一化分隔符。
145
- * 旧版移动端按 Windows 习惯用 `\` 拼路径(WSL/Linux 上把 `/home` 拼成 `/\home`,
146
- * readdir 必然 ENOENT);服务端统一换成当前平台分隔符后浏览/建夹/建会话才能命中
147
- * 真实目录。仅换分隔符:不展开 ..、不解析软链、不改其余字符。
148
- * platform 参数仅用于单测固定平台;调用点一律用默认值。 */
144
+
145
+
146
+
147
+
148
+
149
149
  export function normalizeServerPath(p, platform = process.platform) {
150
150
  if (typeof p !== "string") return p;
151
151
  return platform === "win32" ? p.replaceAll("/", "\\") : p.replaceAll("\\", "/");
152
152
  }
153
153
 
154
- /**
155
- * v3.1.5(PR #11 P1):校验手机端提交的问询答案,不信任移动端 UI。
156
- *
157
- * 内核 `dsh-tool-ask-user` 直接展开答案字段(`selected: [...answer.selected]`,
158
- * 见 @deepseek-ai/dsh-tool-ask-user/lib/index.js:107-111),`ctx.userQuestions.ask()`
159
- * 本身不做任何形状校验(@deepseek-ai/dsh-user-questions/lib/index.js:69-78):
160
- * `selected` 缺失/为 null 会在内核里抛 TypeError,选项未声明/一问多答则会把
161
- * 模型收到伪造答案。故在插件边界逐条校验,非法一律 400 且保留 pending 可重试。
162
- *
163
- * @returns `{ ok: true }` 或 `{ ok: false, code, detail }`。
164
- */
154
+
155
+
156
+
157
+
158
+
159
+
160
+
161
+
162
+
163
+
164
+
165
165
  export function validateQuestionAnswers(questions, answers) {
166
166
  if (!Array.isArray(questions) || questions.length === 0) {
167
167
  return { ok: false, code: "question-answer-invalid", detail: "问询条目缺少 questions" };
@@ -171,7 +171,7 @@ export function validateQuestionAnswers(questions, answers) {
171
171
  }
172
172
  const byId = new Map();
173
173
  for (const answer of answers) {
174
- // id 必须是自身属性且不重复(重复 id 会让"每问一答"变成一问多答)
174
+
175
175
  if (!answer || typeof answer !== "object" || typeof answer.id !== "string" || byId.has(answer.id)) {
176
176
  return { ok: false, code: "question-answer-invalid", detail: "答案 id 无效或重复" };
177
177
  }
@@ -183,8 +183,8 @@ export function validateQuestionAnswers(questions, answers) {
183
183
  }
184
184
  const answer = byId.get(question.id);
185
185
  if (!answer) return { ok: false, code: "question-answer-invalid", detail: `缺少问题 ${question.id} 的答案` };
186
- // selected 必须是自身属性且为 string[]:不接受 null/undefined 兜底,
187
- // 否则内核 `[...answer.selected]` 抛 TypeError(本函数的存在理由之一)
186
+
187
+
188
188
  if (!Object.hasOwn(answer, "selected") || !Array.isArray(answer.selected)) {
189
189
  return { ok: false, code: "question-answer-invalid", detail: `问题 ${question.id} 的 selected 无效` };
190
190
  }
@@ -221,14 +221,14 @@ export function validateQuestionAnswers(questions, answers) {
221
221
  return { ok: true };
222
222
  }
223
223
 
224
- /**
225
- * 把网络/请求失败归类为**稳定错误码**(issue #21 评审 BLOCKING 1)。
226
- *
227
- * 为什么不回传异常原文:凭据里若含内嵌 CR/LF,原生 fetch 的 Headers 校验会抛出
228
- * `Headers.append: "Bearer sk-…\n…" is an invalid header value.` —— **消息里带完整密钥**,
229
- * 而 `redactPathText` 只脱敏主机路径、不脱敏凭据,所以"脱敏后回传异常消息"并不安全。
230
- * 移动端只需要知道失败**类别**;细节留在服务端日志(那里本就有权限边界)。
231
- */
224
+
225
+
226
+
227
+
228
+
229
+
230
+
231
+
232
232
  export const classifyFetchFailure = (err) => {
233
233
  const name = typeof err?.name === "string" ? err.name : "";
234
234
  const code = typeof err?.code === "string" ? err.code : (typeof err?.cause?.code === "string" ? err.cause.code : "");
@@ -238,9 +238,9 @@ export const classifyFetchFailure = (err) => {
238
238
  if (code === "ECONNREFUSED") return "connection-refused";
239
239
  if (code === "ECONNRESET") return "connection-reset";
240
240
  if (code === "UND_ERR_SOCKET") return "socket-error";
241
- // issue #30 评审 WARNING 4:宿主模块已经给出**结构化**失败——拿到 HTTP 响应就**不是**网络不可达,
242
- // 归到 unreachable 会让用户排查错方向(限流/登录失效去查网络)。只接受 allow-list 的稳定 code
243
- // 与**校验过的数值** status,仍然不接收任何异常原文。
241
+
242
+
243
+
244
244
  if (code === "OPENAI_CODEX_REAUTH_REQUIRED") return "reauth-required";
245
245
  const status = Number.isInteger(err?.status)
246
246
  ? err.status
@@ -248,13 +248,13 @@ export const classifyFetchFailure = (err) => {
248
248
  if (status !== undefined && status >= 400 && status <= 599) {
249
249
  return status === 429 ? "rate-limited" : "http-error";
250
250
  }
251
- // TypeError 覆盖 Headers/URL 的本地校验失败——**凭据形态问题会落在这里**,
252
- // 因此这一类绝不能附带原文。
251
+
252
+
253
253
  if (name === "TypeError") return "invalid-request";
254
254
  return "unreachable";
255
255
  };
256
256
 
257
- /** 错误码 → 固定摘要(allow-list,逐字写死,永不包含异常原文或凭据)。 */
257
+
258
258
  const FAILURE_SUMMARY = {
259
259
  timeout: "请求超时",
260
260
  "connect-timeout": "连接超时",
@@ -263,34 +263,34 @@ const FAILURE_SUMMARY = {
263
263
  "connection-reset": "连接被重置",
264
264
  "socket-error": "连接异常中断",
265
265
  "invalid-request": "请求构造被拒(可能是凭据或地址形态问题)",
266
- // 结构化失败(issue #30 评审 WARNING 4):已收到 HTTP 响应 / 宿主明确要求重新登录
266
+
267
267
  "reauth-required": "需重新登录",
268
268
  "rate-limited": "请求被限流",
269
269
  "http-error": "服务端返回错误",
270
270
  unreachable: "网络不可达",
271
271
  };
272
272
 
273
- /** 供移动端展示的安全失败摘要:稳定错误码 + 固定文案,不含任何异常原文。 */
273
+
274
274
  export const safeFailureReason = (err) => {
275
275
  const code = classifyFetchFailure(err);
276
276
  return `${code}(${FAILURE_SUMMARY[code] ?? FAILURE_SUMMARY.unreachable})`;
277
277
  };
278
278
 
279
- /**
280
- * 请求级取消:客户端断开(超时 / 关页面 / 切网络)时,停止服务端仍在进行的扫描。
281
- *
282
- * **为什么需要**(issue #20):`/sessions` 的代价与历史语料规模成正比——实测单次请求
283
- * 72 秒、约 95 CPU-秒、读取 1.24 GB,而客户端通常三十秒就超时走人了。宿主**本来就支持
284
- * 取消**(`listSessions(signal?)`、`readTitleSnapshots(ids, signal?)`,持久化层还会
285
- * `signal.throwIfAborted()`),插件此前一处都没传,于是断开的请求照样跑完:
286
- * 实测**约 86% 的算力与 I/O 花在已经离开的客户端上**,并发重试时还会互相叠加。
287
- *
288
- * **为什么在 `res` 的 close 上判 `writableEnded`**:正常完成的响应同样会触发 close,
289
- * 不判就会把每一次成功响应都当成取消。
290
- *
291
- * 监听器刻意**不显式移除**:`res` 是每请求一个的对象,请求结束即随对象回收,不存在
292
- * 跨请求累积;而在响应之后再触发 abort 也没有任何等待者,是无害的空操作。
293
- */
279
+
280
+
281
+
282
+
283
+
284
+
285
+
286
+
287
+
288
+
289
+
290
+
291
+
292
+
293
+
294
294
  export const requestAbort = (res) => {
295
295
  const ac = new AbortController();
296
296
  res.once("close", () => {
@@ -299,14 +299,14 @@ export const requestAbort = (res) => {
299
299
  return ac.signal;
300
300
  };
301
301
 
302
- /** 插件主体。 */
303
302
 
304
- /**
305
- * 解析 `Range: bytes=...`(v3.2.3)。
306
- *
307
- * 只支持单区间(多区间用不上,还容易被拿来放大响应);越界/格式错返回
308
- * `{ invalid: true }`,调用方回 416 并带 `Content-Range: bytes * /size`。
309
- */
303
+
304
+
305
+
306
+
307
+
308
+
309
+
310
310
  export const parseByteRange = (value, size) => {
311
311
  const text = String(value ?? "").trim();
312
312
  if (text === "") return null;
@@ -325,7 +325,7 @@ export const parseByteRange = (value, size) => {
325
325
  if (!Number.isSafeInteger(end) || end < start) return { invalid: true };
326
326
  return { start, end: Math.min(end, size - 1) };
327
327
  };
328
- /** `If-None-Match` 是否命中当前 ETag(支持 `*` 与逗号列表)。 */
328
+
329
329
  export const ifNoneMatch = (req, etag) => {
330
330
  if (!etag) return false;
331
331
  const raw = requestHeaderText(req, "if-none-match");
@@ -1,49 +1,61 @@
1
- /**
2
- * 助手偏好(模式 / 人格)的读写接口(T9)。
3
- *
4
- * 为什么要这个接口:模式与人格必须**同时**作用在两个地方——
5
- * 1. 推送与通知的措辞(服务端已有);
6
- * 2. agent 对话时的上下文(人格决定语气、模式决定能看到哪些记忆)。
7
- * 之前 App 里切换只写进了手机本地,服务端一直是默认值,于是「切成生活模式」
8
- * 只改了手机上一句提示,电脑上的助手仍然拿着工作记忆在说话。这不是没做,
9
- * 是做了但没生效。
10
- *
11
- * 落盘策略:写进 `<状态目录>/assistant.json`,重启后保持。之所以不写回
12
- * `cordis.patch.yml`:那是用户手写的部署配置,插件不该去改它。
13
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
14
  import { readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
15
15
  import { join } from "node:path";
16
16
  import { parseHm } from "./notify-copy.js";
17
17
 
18
18
  const MODES = ["work", "life"];
19
- /** Persona card ids (T-31): same rule as lib/persona-cards.js validatePersonaCard. */
19
+
20
20
  const PERSONA_CARD_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
21
21
  const PERSONAS = ["colleague", "character"];
22
22
 
23
- /**
24
- * 安静时段的合法性判断。返回 `true` 表示两个时间点都能解析。
25
- *
26
- * 故意不接受「猜一个默认值」:配置写错时宁可多吵一次,
27
- * 也不要把用户的通知整段吞掉(见 config.js 里同一条注释)。
28
- */
23
+ const NO_PERSONA_ID = "none";
24
+
25
+ const UNPICKED_LEGACY_CARDS = ["workaholic", "life-assistant"];
26
+
27
+
28
+
29
+
30
+
31
+
32
+
29
33
  function validWindow(start, end) {
30
34
  return parseHm(start) !== null && parseHm(end) !== null;
31
35
  }
32
36
 
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
- */
37
+
38
+
39
+
40
+
41
+
38
42
  export function createAssistantPrefs({ dir, defaults }) {
39
43
  const file = join(dir, "assistant.json");
40
- /**
41
- * Only what the app (or the user) explicitly set (A-21): the effective value of anything else is
42
- * worked out on every read from the config and the defaults, so a later config change still
43
- * applies. Files written before 3.3.1 (no `v: 2`) stored the merged object, so in them a
44
- * `breakReminder: true` may be a default that was copied in, not the app's switch (A-13): it is not
45
- * taken as explicit. Everything else in an old file is kept as explicit, as before.
46
- */
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
47
59
  let explicit = null;
48
60
 
49
61
  function readExplicit() {
@@ -54,24 +66,31 @@ export function createAssistantPrefs({ dir, defaults }) {
54
66
  } catch {
55
67
  raw = null;
56
68
  }
57
- const legacy = raw && raw.v !== 2;
69
+ const legacy = raw && !(raw.v >= 2);
70
+ const preNoCardDefault = raw && !(raw.v >= 3);
58
71
  const e = {};
59
72
  if (raw && typeof raw === "object") {
60
73
  if (MODES.includes(raw.mode)) e.mode = raw.mode;
61
74
  if (PERSONAS.includes(raw.persona)) e.persona = raw.persona;
62
- // 安静时段单独校验:文件里可能是旧版本写的、也可能是手改坏的。
63
- // 只有两个端点都合法才采用,否则整体回落到配置值——半个窗口比没有更糟。
75
+
76
+
64
77
  const quiet = raw.quietHours;
65
78
  if (quiet && validWindow(quiet.start, quiet.end)) e.quietHours = { start: quiet.start, end: quiet.end };
66
79
  if (typeof raw.breakReminder === "boolean" && !(legacy && raw.breakReminder === true)) e.breakReminder = raw.breakReminder;
67
- // T-31: the active persona card (an id). Absent = the old colleague/character switch decides.
68
- if (PERSONA_CARD_ID.test(raw.personaCard ?? "")) e.personaCard = raw.personaCard;
80
+
81
+ if (
82
+ PERSONA_CARD_ID.test(raw.personaCard ?? "") &&
83
+ raw.personaCard !== NO_PERSONA_ID &&
84
+ !(preNoCardDefault && UNPICKED_LEGACY_CARDS.includes(raw.personaCard))
85
+ ) {
86
+ e.personaCard = raw.personaCard;
87
+ }
69
88
  }
70
89
  explicit = e;
71
90
  return explicit;
72
91
  }
73
92
 
74
- /** Explicit values over the config's defaults over the built-in defaults. */
93
+
75
94
  function effective() {
76
95
  const e = readExplicit();
77
96
  const fallback = defaults();
@@ -79,7 +98,7 @@ export function createAssistantPrefs({ dir, defaults }) {
79
98
  mode: e.mode ?? fallback.mode,
80
99
  persona: e.persona ?? fallback.persona,
81
100
  quietHours: { ...(e.quietHours ?? fallback.quietHours ?? { start: "23:30", end: "08:30" }) },
82
- // T-15: the user's own off switch for the break reminder (on unless they turned it off).
101
+
83
102
  breakReminder: e.breakReminder ?? true,
84
103
  ...(e.personaCard ? { personaCard: e.personaCard } : {}),
85
104
  };
@@ -87,29 +106,29 @@ export function createAssistantPrefs({ dir, defaults }) {
87
106
 
88
107
  function save(next) {
89
108
  mkdirSync(dir, { recursive: true });
90
- // 原子写:先写临时文件再 rename,避免断电/崩溃留下半个 JSON。
109
+
91
110
  const tmp = `${file}.tmp`;
92
- writeFileSync(tmp, JSON.stringify({ v: 2, ...next }, null, 2), "utf8");
111
+ writeFileSync(tmp, JSON.stringify({ v: 3, ...next }, null, 2), "utf8");
93
112
  renameSync(tmp, file);
94
113
  explicit = next;
95
114
  }
96
115
 
97
116
  return {
98
117
  file,
99
- /** 当前有效的模式与人格。 */
118
+
100
119
  get: () => effective(),
101
- /**
102
- * Has the app ever sent its break-reminder switch (A-13)? Store apps up to 3.2.7 have no such
103
- * switch, so for them the reminder stays off unless the PC config turns it on.
104
- */
120
+
121
+
122
+
123
+
105
124
  breakReminderSetByApp: () => typeof readExplicit().breakReminder === "boolean",
106
125
 
107
- /**
108
- * 改一项或两项。非法值直接拒绝,不「猜一个最近的」:
109
- * 猜错会让用户以为切换成功,实际还在原来的模式里。
110
- * Returns the effective prefs and `changed`: whether any effective value differs (A-20: the
111
- * app's automatic re-sync on every reconnect changes nothing and is not someone's activity).
112
- */
126
+
127
+
128
+
129
+
130
+
131
+
113
132
  set(patch) {
114
133
  const before = JSON.stringify(effective());
115
134
  const next = { ...readExplicit() };
@@ -129,16 +148,20 @@ export function createAssistantPrefs({ dir, defaults }) {
129
148
  const start = patch.quietHours?.start;
130
149
  const end = patch.quietHours?.end;
131
150
  if (!validWindow(start, end)) {
132
- // 不静默保留旧值:用户会以为自己改成功了,夜里照样被吵醒。
151
+
133
152
  throw new Error("quietHours 必须是 {start: \"HH:MM\", end: \"HH:MM\"}");
134
153
  }
135
154
  next.quietHours = { start, end };
136
155
  }
137
156
  if (patch?.personaCard !== undefined) {
138
- if (typeof patch.personaCard !== "string" || !PERSONA_CARD_ID.test(patch.personaCard)) {
139
- throw new Error("personaCard 必须是人格卡的 id / personaCard must be a persona card id");
157
+ if (patch.personaCard === null || patch.personaCard === NO_PERSONA_ID) {
158
+
159
+ delete next.personaCard;
160
+ } else if (typeof patch.personaCard !== "string" || !PERSONA_CARD_ID.test(patch.personaCard)) {
161
+ throw new Error('personaCard 必须是人格卡的 id 或 "none" / personaCard must be a persona card id or "none"');
162
+ } else {
163
+ next.personaCard = patch.personaCard;
140
164
  }
141
- next.personaCard = patch.personaCard;
142
165
  }
143
166
  if (patch?.breakReminder !== undefined) {
144
167
  if (typeof patch.breakReminder !== "boolean") throw new Error("breakReminder 必须是 true / false");
@@ -152,10 +175,10 @@ export function createAssistantPrefs({ dir, defaults }) {
152
175
  };
153
176
  }
154
177
 
155
- // personaBrief was removed with T-31 (D8): the active persona card's own text is the only
156
- // persona text the model sees (lib/persona-cards.js, personaPromptText).
157
178
 
158
- /** 模式 → 一段给模型看的说明。生活模式明确要求不提工作内容。 */
179
+
180
+
181
+
159
182
  export function modeBrief(mode) {
160
183
  if (mode === "life") {
161
184
  return [