@dsh-mobile/mobile-remote 3.2.7 → 3.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/FAQ.md +19 -12
- package/LICENSE +0 -0
- package/README.md +40 -40
- package/cordis.patch.yml +8 -4
- package/docs/PRIVACY-POLICY.en.md +89 -47
- package/docs/PRIVACY-POLICY.md +89 -47
- package/docs/SUPPORT.md +5 -5
- package/docs/TERMS-OF-SERVICE.en.md +5 -3
- package/docs/TERMS-OF-SERVICE.md +5 -3
- package/docs/USER-GUIDE.zh-CN.md +562 -0
- package/lib/account-usage.js +0 -0
- package/lib/api-helpers.js +6 -2
- package/lib/assistant-prefs.js +167 -0
- package/lib/auto-config.js +55 -3
- package/lib/backup.js +441 -0
- package/lib/break-reminder.js +133 -0
- package/lib/client.js +321 -77
- package/lib/config.js +96 -5
- package/lib/git-read-bundled-provider.js +32 -3
- package/lib/git-read-service.js +4 -0
- package/lib/host-compat.js +25 -0
- package/lib/http-util.js +6 -2
- package/lib/index.js +1121 -83
- package/lib/memory/context.js +81 -0
- package/lib/memory/decay.js +144 -0
- package/lib/memory/extract.js +146 -0
- package/lib/memory/routes.js +198 -0
- package/lib/memory/store.js +714 -0
- package/lib/notify-copy.js +245 -0
- package/lib/permission-guide.js +184 -0
- package/lib/persona-cards.js +366 -0
- package/lib/proactive-material.js +162 -0
- package/lib/proactive.js +372 -0
- package/lib/protected-paths.js +290 -0
- package/lib/protocol.js +39 -0
- package/lib/rate-limit.js +1 -1
- package/lib/relay/connector.js +208 -14
- package/lib/relay/devices.js +54 -8
- package/lib/relay/fingerprint.js +55 -0
- package/lib/relay/identity.js +69 -0
- package/lib/relay/on-demand.js +89 -0
- package/lib/relay/pairing.js +45 -6
- package/lib/relay/phone.js +89 -12
- package/lib/relay/ws-server.js +245 -0
- package/lib/reminders.js +140 -0
- package/lib/rpc-adapter.js +21 -2
- package/lib/session-rotation.js +198 -0
- package/lib/session-title-cache.js +0 -0
- package/lib/session-title-refresh.js +0 -0
- package/lib/timeline.js +1 -1
- package/package.json +30 -14
- package/CHANGELOG.md +0 -1383
- package/CONTRIBUTING.md +0 -61
- package/docs/00-/345/274/200/345/217/221/346/200/273/347/272/262.md +0 -432
- package/docs/01-PRD.md +0 -148
- package/docs/02-architecture.md +0 -249
- package/docs/03-api.md +0 -882
- package/docs/04-security.md +0 -110
- package/docs/05-test-cases.md +0 -376
- package/docs/06-install-run.md +0 -335
- package/docs/07-user-manual.md +0 -92
- package/docs/08-/346/211/251/345/261/225/345/274/200/345/217/221/346/214/207/345/215/227.md +0 -86
- package/docs/09-compatibility.md +0 -201
- package/docs/11-remote-relay-guide.md +0 -86
- package/docs/APP-ENCRYPTION-DESCRIPTION.md +0 -50
- package/docs/APP-ENCRYPTION-DESCRIPTION.pdf +0 -0
- package/docs/APP-REVIEW-NOTES.md +0 -105
- package/docs/BRAND-ASSETS.md +0 -142
- package/docs/COMPANION-PLAN.md +0 -199
- package/docs/STORE-LAUNCH.md +0 -341
- package/docs/STORE-LISTING.md +0 -190
package/lib/backup.js
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 备份、恢复与「预演恢复」(P1-16)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要预演:恢复是一次**不可撤销的写入**,而用户手里的备份文件可能来自
|
|
5
|
+
* 另一台电脑、另一个版本、甚至是手改过的。让他在真写之前先看清「会写进去多少条、
|
|
6
|
+
* 跳过多少条、为什么跳过」,比事后提供一个「撤销」便宜得多。
|
|
7
|
+
*
|
|
8
|
+
* 为什么预演和真恢复必须是同一份计划:如果预演走一套判断、真恢复走另一套,
|
|
9
|
+
* 预演就变成了一句安慰话——它会说「将恢复 42 条」,而实际写进去 40 条。
|
|
10
|
+
* 所以两者都调 `planRestore()`,真恢复只是把计划执行一遍。
|
|
11
|
+
*
|
|
12
|
+
* **备份里没有凭据,这是刻意的**:
|
|
13
|
+
* - `auth-token`(连接口令)与 `relay/`(中继身份私钥)能让别人冒充这台电脑
|
|
14
|
+
* 或这个账号。备份文件通常被放进网盘、聊天记录、U 盘,一旦带上它们,
|
|
15
|
+
* 泄露面就从"一台机器"变成"所有存过备份的地方"。
|
|
16
|
+
* - `held-queue`(暂存待发消息)与 `send-receipts`(幂等回执)具有强时效性,
|
|
17
|
+
* 恢复到另一台设备只会产生重复投递与陈旧状态。
|
|
18
|
+
* 所以恢复之后需要在**新设备上重新扫码配对**——这是设计,不是缺陷,要说出来。
|
|
19
|
+
*
|
|
20
|
+
* 恢复是**只增不删**的:已有条目按 (scope, text) 判重后跳过,绝不因为备份里
|
|
21
|
+
* 没有某条就删掉本机现有的。这样即使用户拿错了备份文件,也不会丢东西。
|
|
22
|
+
*/
|
|
23
|
+
import { createCipheriv, createDecipheriv, randomBytes, scrypt } from "node:crypto";
|
|
24
|
+
import { SCOPES } from "./memory/store.js";
|
|
25
|
+
import { parseHm } from "./notify-copy.js";
|
|
26
|
+
|
|
27
|
+
/** 文件里的格式标记。读到别的值说明这不是我们的备份,不要试着"尽力解析"。 */
|
|
28
|
+
export const BACKUP_FORMAT = "dsh-mobile-backup";
|
|
29
|
+
|
|
30
|
+
/** 版本号。将来改结构时递增,旧版本仍需可读。 */
|
|
31
|
+
export const BACKUP_VERSION = 1;
|
|
32
|
+
|
|
33
|
+
/** 单条记忆的长度上限,与 `/api/memory` 的写入校验保持一致。 */
|
|
34
|
+
const MAX_TEXT = 4000;
|
|
35
|
+
|
|
36
|
+
/** 一次恢复的条数上限:防止一个巨型/畸形文件把库灌满。 */
|
|
37
|
+
export const MAX_RESTORE_ITEMS = 5000;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Largest restore request body, in bytes (T-55, finding E5). The generic 64 KiB body limit made
|
|
41
|
+
* every real backup fail as "not valid JSON". 32 MiB holds MAX_RESTORE_ITEMS full-length items of
|
|
42
|
+
* ASCII text with room to spare; anything larger is refused with a 413 that says so.
|
|
43
|
+
*/
|
|
44
|
+
export const MAX_RESTORE_BODY_BYTES = 32 * 1024 * 1024;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 备份内容里**明确不包含**的东西。写进文件本身,让拿到备份的人一眼看到
|
|
48
|
+
* "这里面没有口令",而不是去猜。
|
|
49
|
+
*/
|
|
50
|
+
export const BACKUP_EXCLUDES = [
|
|
51
|
+
"auth-token(连接口令)",
|
|
52
|
+
"relay/(中继身份私钥与设备名单)",
|
|
53
|
+
"held-queue(暂存待发消息)",
|
|
54
|
+
"send-receipts(幂等回执)",
|
|
55
|
+
"session-titles / session-activity / session-message-time(与本机会话 id 绑定)",
|
|
56
|
+
];
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 生成备份对象。
|
|
60
|
+
*
|
|
61
|
+
* @param {object} e
|
|
62
|
+
* @param {object|null} e.store 记忆库(null = 记忆功能没开,仍可备份人格)
|
|
63
|
+
* @param {{get: () => object}} e.prefs 助手偏好
|
|
64
|
+
* @param {() => number} [e.now]
|
|
65
|
+
*/
|
|
66
|
+
export function buildBackup({ store, prefs, now = () => Date.now() }) {
|
|
67
|
+
const memories = store ? store.exportAll() : [];
|
|
68
|
+
return {
|
|
69
|
+
format: BACKUP_FORMAT,
|
|
70
|
+
version: BACKUP_VERSION,
|
|
71
|
+
createdAt: new Date(now()).toISOString(),
|
|
72
|
+
// 只备份"关于这个人"的数据:记忆 + 模式/人格/安静时段。
|
|
73
|
+
// 会话、任务、审批都是电脑上那一刻的状态,不属于可搬运的用户数据。
|
|
74
|
+
excludes: BACKUP_EXCLUDES,
|
|
75
|
+
assistant: prefs?.get?.() ?? null,
|
|
76
|
+
memories: memories.map((m) => ({
|
|
77
|
+
scope: m.scope,
|
|
78
|
+
text: m.text,
|
|
79
|
+
source: m.source === "manual" ? "manual" : "conversation",
|
|
80
|
+
origin: m.origin ?? null,
|
|
81
|
+
pinned: Boolean(m.pinned),
|
|
82
|
+
// 衰减参数一并带走:否则恢复后所有旧记忆都会被当成"刚记住",
|
|
83
|
+
// 到第 60 天集体消失一次——那不是恢复,是重置。
|
|
84
|
+
stability: typeof m.stability === "number" ? m.stability : undefined,
|
|
85
|
+
difficulty: typeof m.difficulty === "number" ? m.difficulty : undefined,
|
|
86
|
+
lastRecalledAt:
|
|
87
|
+
typeof m.lastRecalledAt === "number" ? m.lastRecalledAt : undefined,
|
|
88
|
+
// T-63:删掉的记忆不进备份(exportAll 只给现存的)。旧备份里带 `deleted: true`
|
|
89
|
+
// 的条目在恢复时仍会被跳过(见 validateMemory)。
|
|
90
|
+
})),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ── 备份口令(T-63,可选)────────────────────────────────────────────────
|
|
95
|
+
//
|
|
96
|
+
// 不设口令时备份是明文 JSON(原样可读,便于用户自己检查)。设了口令时整份备份用
|
|
97
|
+
// scrypt 派生的密钥做 AES-256-GCM 加密,文件里只剩格式标记与密文:拿到文件但不知道
|
|
98
|
+
// 口令的人读不到任何一条记忆。口令只在请求里出现一次,插件不保存它。
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 口令最短长度,按字符(code point)数,不按 UTF-16 单元(A-16)。A backup file can be attacked
|
|
102
|
+
* offline at full speed, so this follows NIST SP 800-63B-4 for single-factor passwords: at least
|
|
103
|
+
* 15 characters, plus a check against obviously guessable ones (`passphraseProblem`).
|
|
104
|
+
*/
|
|
105
|
+
export const MIN_BACKUP_PASSPHRASE = 15;
|
|
106
|
+
|
|
107
|
+
/** A few long passphrases that are on every list; the shape checks below catch most of the rest. */
|
|
108
|
+
const COMMON_PASSPHRASES = new Set([
|
|
109
|
+
"passwordpassword", "password1234567", "123456789012345", "1234567890123456", "qwertyuiopasdfg",
|
|
110
|
+
"qwertyuiopasdfgh", "1q2w3e4r5t6y7u8i", "iloveyouiloveyou", "abcdefghijklmno", "abcdefghijklmnop",
|
|
111
|
+
]);
|
|
112
|
+
|
|
113
|
+
/** Why `passphrase` is too weak for an offline-attackable backup, or null if it is acceptable. */
|
|
114
|
+
export function passphraseProblem(passphrase) {
|
|
115
|
+
if (typeof passphrase !== "string") return `口令至少 ${MIN_BACKUP_PASSPHRASE} 个字符 / the passphrase needs at least ${MIN_BACKUP_PASSPHRASE} characters`;
|
|
116
|
+
const chars = [...passphrase.normalize("NFC")];
|
|
117
|
+
if (chars.length < MIN_BACKUP_PASSPHRASE) return `口令至少 ${MIN_BACKUP_PASSPHRASE} 个字符 / the passphrase needs at least ${MIN_BACKUP_PASSPHRASE} characters`;
|
|
118
|
+
const folded = chars.join("").toLowerCase();
|
|
119
|
+
if (new Set(chars.filter((c) => c.trim() !== "")).size < 5 || /^(.+?)\1+$/su.test(folded) || COMMON_PASSPHRASES.has(folded.replace(/\s+/g, ""))) {
|
|
120
|
+
return "这个口令太容易猜 / this passphrase is too easy to guess: use a few unrelated words";
|
|
121
|
+
}
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Written now: scrypt N=2^17, r=8, p=1 (OWASP's minimum for scrypt, A-16). 3.3.0 wrote N=2^15;
|
|
127
|
+
* those backups still open. No other parameter set is accepted from a file (T-63: a file must not
|
|
128
|
+
* be able to make the plugin spend unbounded time or memory).
|
|
129
|
+
*/
|
|
130
|
+
const KDF = { name: "scrypt", N: 1 << 17, r: 8, p: 1, keyLen: 32 };
|
|
131
|
+
const ACCEPTED_KDF = [KDF, { name: "scrypt", N: 1 << 15, r: 8, p: 1, keyLen: 32 }];
|
|
132
|
+
export const BACKUP_KDF = Object.freeze({ ...KDF });
|
|
133
|
+
|
|
134
|
+
/** One scrypt at a time (each takes ~128 MiB and a few hundred ms), off the event loop. */
|
|
135
|
+
let kdfQueue = Promise.resolve();
|
|
136
|
+
const deriveKey = (passphrase, salt, kdf = KDF) => {
|
|
137
|
+
const run = () =>
|
|
138
|
+
new Promise((resolve, reject) =>
|
|
139
|
+
scrypt(String(passphrase).normalize("NFC"), salt, kdf.keyLen ?? 32, { N: kdf.N, r: kdf.r, p: kdf.p, maxmem: 256 * kdf.N * kdf.r + 1024 * 1024 }, (err, key) =>
|
|
140
|
+
err ? reject(err) : resolve(key),
|
|
141
|
+
),
|
|
142
|
+
);
|
|
143
|
+
const next = kdfQueue.then(run, run);
|
|
144
|
+
kdfQueue = next.catch(() => {});
|
|
145
|
+
return next;
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/** 备份文件是不是加了口令的。 */
|
|
149
|
+
export function isEncryptedBackup(payload) {
|
|
150
|
+
return Boolean(payload && typeof payload === "object" && payload.encrypted && typeof payload.encrypted === "object");
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* 给备份加口令。返回 `{ format, version, encrypted: {...} }`,可直接存成文件。
|
|
155
|
+
* @param {object} backup buildBackup 的结果
|
|
156
|
+
* @param {string} passphrase 至少 MIN_BACKUP_PASSPHRASE 个字符,且不是 passphraseProblem 认为好猜的
|
|
157
|
+
* @returns {Promise<object>}
|
|
158
|
+
*/
|
|
159
|
+
export async function encryptBackup(backup, passphrase) {
|
|
160
|
+
const problem = passphraseProblem(passphrase);
|
|
161
|
+
if (problem) throw Object.assign(new Error(problem), { code: "weak-passphrase" });
|
|
162
|
+
const salt = randomBytes(16);
|
|
163
|
+
const iv = randomBytes(12);
|
|
164
|
+
const key = await deriveKey(passphrase, salt);
|
|
165
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
166
|
+
// 格式标记作为附加认证数据:密文被挪到别的格式里会解不开。
|
|
167
|
+
cipher.setAAD(Buffer.from(`${BACKUP_FORMAT}/${BACKUP_VERSION}`));
|
|
168
|
+
const data = Buffer.concat([cipher.update(JSON.stringify(backup), "utf8"), cipher.final()]);
|
|
169
|
+
return {
|
|
170
|
+
format: BACKUP_FORMAT,
|
|
171
|
+
version: BACKUP_VERSION,
|
|
172
|
+
encrypted: {
|
|
173
|
+
kdf: { name: KDF.name, N: KDF.N, r: KDF.r, p: KDF.p, salt: salt.toString("base64") },
|
|
174
|
+
cipher: "aes-256-gcm",
|
|
175
|
+
iv: iv.toString("base64"),
|
|
176
|
+
tag: cipher.getAuthTag().toString("base64"),
|
|
177
|
+
data: data.toString("base64"),
|
|
178
|
+
},
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 解开加了口令的备份。口令不对、文件被改过、参数不认识都抛错(`code` 区分)。
|
|
184
|
+
* @returns {object} 原始备份对象(再交给 planRestore / applyRestore)
|
|
185
|
+
*/
|
|
186
|
+
export async function decryptBackup(envelope, passphrase) {
|
|
187
|
+
const e = envelope?.encrypted;
|
|
188
|
+
if (!e || e.cipher !== "aes-256-gcm" || e.kdf?.name !== "scrypt") {
|
|
189
|
+
throw Object.assign(new Error("不认识的加密格式 / unknown encryption format"), { code: "bad-backup" });
|
|
190
|
+
}
|
|
191
|
+
if (typeof passphrase !== "string" || passphrase === "") {
|
|
192
|
+
throw Object.assign(new Error("这份备份设了口令 / this backup needs its passphrase"), { code: "passphrase-required" });
|
|
193
|
+
}
|
|
194
|
+
// 参数来自文件:只接受我们自己写的那一组。scryptSync 在事件循环上跑,放宽就等于让一个
|
|
195
|
+
// 恶意文件把插件卡住或吃光内存(T-63 fix)。
|
|
196
|
+
const N = Number(e.kdf.N);
|
|
197
|
+
const r = Number(e.kdf.r);
|
|
198
|
+
const p = Number(e.kdf.p);
|
|
199
|
+
if (!ACCEPTED_KDF.some((k) => k.N === N && k.r === r && k.p === p)) {
|
|
200
|
+
throw Object.assign(new Error("加密参数不是本插件写的 / encryption parameters not written by this plugin"), { code: "bad-backup" });
|
|
201
|
+
}
|
|
202
|
+
const tag = Buffer.from(String(e.tag), "base64");
|
|
203
|
+
if (tag.length !== 16) {
|
|
204
|
+
throw Object.assign(new Error("口令不对,或文件已损坏 / wrong passphrase, or the file is damaged"), { code: "bad-passphrase" });
|
|
205
|
+
}
|
|
206
|
+
try {
|
|
207
|
+
const key = await deriveKey(passphrase, Buffer.from(String(e.kdf.salt), "base64"), { N, r, p, keyLen: 32 });
|
|
208
|
+
// authTagLength: a truncated tag is refused instead of checked on fewer bits (DEP0182).
|
|
209
|
+
const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(String(e.iv), "base64"), { authTagLength: 16 });
|
|
210
|
+
decipher.setAAD(Buffer.from(`${envelope.format}/${envelope.version}`));
|
|
211
|
+
decipher.setAuthTag(tag);
|
|
212
|
+
const plain = Buffer.concat([decipher.update(Buffer.from(String(e.data), "base64")), decipher.final()]);
|
|
213
|
+
return JSON.parse(plain.toString("utf8"));
|
|
214
|
+
} catch {
|
|
215
|
+
throw Object.assign(new Error("口令不对,或文件已损坏 / wrong passphrase, or the file is damaged"), { code: "bad-passphrase" });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* 校验一条待恢复的记忆。返回 `{ ok: true, item }` 或 `{ ok: false, reason }`。
|
|
221
|
+
*
|
|
222
|
+
* 备份文件是外部输入,一律当作不可信:不信任任何字段的类型,也不信任长度。
|
|
223
|
+
*/
|
|
224
|
+
function validateMemory(raw, index) {
|
|
225
|
+
if (!raw || typeof raw !== "object") {
|
|
226
|
+
return { ok: false, reason: "不是对象", index };
|
|
227
|
+
}
|
|
228
|
+
const scope = raw.scope;
|
|
229
|
+
if (!SCOPES.includes(scope)) {
|
|
230
|
+
return { ok: false, reason: `scope 非法(${String(scope)})`, index };
|
|
231
|
+
}
|
|
232
|
+
if (typeof raw.text !== "string") {
|
|
233
|
+
return { ok: false, reason: "text 不是字符串", index };
|
|
234
|
+
}
|
|
235
|
+
const text = raw.text.trim();
|
|
236
|
+
if (text === "") return { ok: false, reason: "text 为空", index };
|
|
237
|
+
if (text.length > MAX_TEXT) {
|
|
238
|
+
return { ok: false, reason: `text 超过 ${MAX_TEXT} 字符`, index };
|
|
239
|
+
}
|
|
240
|
+
if (raw.deleted === true) {
|
|
241
|
+
// 旧版本的备份会带上软删除的条目:删掉的就是删掉了,不恢复。
|
|
242
|
+
return { ok: false, reason: "备份里这条已删除", index };
|
|
243
|
+
}
|
|
244
|
+
return {
|
|
245
|
+
ok: true,
|
|
246
|
+
index,
|
|
247
|
+
item: {
|
|
248
|
+
scope,
|
|
249
|
+
text,
|
|
250
|
+
source: raw.source === "manual" ? "manual" : "conversation",
|
|
251
|
+
origin: typeof raw.origin === "string" ? raw.origin : null,
|
|
252
|
+
pinned: raw.pinned === true,
|
|
253
|
+
},
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* 算出「这次恢复会做什么」。纯函数:不写库、不改任何状态。
|
|
259
|
+
*
|
|
260
|
+
* @param {unknown} payload 备份文件解析后的对象
|
|
261
|
+
* @param {object} e
|
|
262
|
+
* @param {object|null} e.store
|
|
263
|
+
* @param {{get: () => object}} e.prefs
|
|
264
|
+
* @returns {{ok: boolean, error?: string, counts: object, items: object[], skipped: object[], assistant: object|null}}
|
|
265
|
+
*/
|
|
266
|
+
export function planRestore(payload, { store, prefs }) {
|
|
267
|
+
const empty = {
|
|
268
|
+
ok: false,
|
|
269
|
+
counts: { total: 0, willAdd: 0, willSkip: 0, invalid: 0 },
|
|
270
|
+
items: [],
|
|
271
|
+
skipped: [],
|
|
272
|
+
assistant: null,
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
if (!payload || typeof payload !== "object") {
|
|
276
|
+
return { ...empty, error: "备份内容不是对象" };
|
|
277
|
+
}
|
|
278
|
+
if (payload.format !== BACKUP_FORMAT) {
|
|
279
|
+
return {
|
|
280
|
+
...empty,
|
|
281
|
+
error: `不是 DSH Mobile 的备份(format=${String(payload.format)})`,
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
if (!Number.isInteger(payload.version) || payload.version < 1) {
|
|
285
|
+
return { ...empty, error: "备份版本号缺失或非法" };
|
|
286
|
+
}
|
|
287
|
+
if (payload.version > BACKUP_VERSION) {
|
|
288
|
+
// 新版本备份可能带旧代码看不懂的字段。与其"尽力恢复"出一个半截状态,
|
|
289
|
+
// 不如明确拒绝并告诉用户升级插件。
|
|
290
|
+
return {
|
|
291
|
+
...empty,
|
|
292
|
+
error: `备份来自更新的版本(v${payload.version}),请先升级插件`,
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
const rawList = payload.memories;
|
|
296
|
+
if (rawList !== undefined && !Array.isArray(rawList)) {
|
|
297
|
+
return { ...empty, error: "memories 不是数组" };
|
|
298
|
+
}
|
|
299
|
+
const list = Array.isArray(rawList) ? rawList : [];
|
|
300
|
+
if (list.length > MAX_RESTORE_ITEMS) {
|
|
301
|
+
return {
|
|
302
|
+
...empty,
|
|
303
|
+
error: `一次最多恢复 ${MAX_RESTORE_ITEMS} 条,这份备份有 ${list.length} 条`,
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// 本机已有条目:按 (scope, text) 判重。用归一化后的文本比较——
|
|
308
|
+
// 否则「末尾多一个空格」会让同一条记忆被恢复成两条。
|
|
309
|
+
const existing = new Set();
|
|
310
|
+
if (store) {
|
|
311
|
+
for (const mode of ["work", "life"]) {
|
|
312
|
+
for (const m of store.listVisible(mode)) {
|
|
313
|
+
existing.add(`${m.scope}\u0000${m.text.trim()}`);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const items = [];
|
|
319
|
+
const skipped = [];
|
|
320
|
+
let invalid = 0;
|
|
321
|
+
const seenInFile = new Set();
|
|
322
|
+
|
|
323
|
+
list.forEach((raw, index) => {
|
|
324
|
+
const v = validateMemory(raw, index);
|
|
325
|
+
if (!v.ok) {
|
|
326
|
+
invalid += 1;
|
|
327
|
+
skipped.push({ index, reason: v.reason });
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
const key = `${v.item.scope}\u0000${v.item.text}`;
|
|
331
|
+
if (seenInFile.has(key)) {
|
|
332
|
+
invalid += 1;
|
|
333
|
+
skipped.push({ index, reason: "备份文件内重复" });
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
seenInFile.add(key);
|
|
337
|
+
if (existing.has(key)) {
|
|
338
|
+
skipped.push({ index, reason: "本机已有同一条" });
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
items.push(v.item);
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
// 人格/模式:只在字段合法时恢复。非法就整块跳过,不"猜一个最近的"——
|
|
345
|
+
// 猜错会让用户以为恢复成功,实际还在原来的模式里。
|
|
346
|
+
let assistant = null;
|
|
347
|
+
const a = payload.assistant;
|
|
348
|
+
if (a && typeof a === "object") {
|
|
349
|
+
const next = {};
|
|
350
|
+
if (a.mode === "work" || a.mode === "life") next.mode = a.mode;
|
|
351
|
+
if (a.persona === "colleague" || a.persona === "character") {
|
|
352
|
+
next.persona = a.persona;
|
|
353
|
+
}
|
|
354
|
+
const q = a.quietHours;
|
|
355
|
+
// 用 `parseHm` 而不是手写正则:`/^\d{1,2}:\d{2}$/` 会放过 `25:00`,
|
|
356
|
+
// 而一个非法窗口恢复进去之后,安静时段会整段失效(或整段生效)——
|
|
357
|
+
// 用户会发现夜里突然被吵醒,却不知道是恢复带进来的。
|
|
358
|
+
if (
|
|
359
|
+
q &&
|
|
360
|
+
typeof q === "object" &&
|
|
361
|
+
parseHm(String(q.start)) !== null &&
|
|
362
|
+
parseHm(String(q.end)) !== null
|
|
363
|
+
) {
|
|
364
|
+
next.quietHours = { start: String(q.start), end: String(q.end) };
|
|
365
|
+
}
|
|
366
|
+
if (typeof a.breakReminder === "boolean") next.breakReminder = a.breakReminder;
|
|
367
|
+
if (typeof a.personaCard === "string" && /^[a-z0-9][a-z0-9-]{0,63}$/.test(a.personaCard)) next.personaCard = a.personaCard;
|
|
368
|
+
if (Object.keys(next).length > 0) assistant = next;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
return {
|
|
372
|
+
ok: true,
|
|
373
|
+
backupVersion: payload.version,
|
|
374
|
+
createdAt: payload.createdAt ?? null,
|
|
375
|
+
counts: {
|
|
376
|
+
total: list.length,
|
|
377
|
+
willAdd: items.length,
|
|
378
|
+
willSkip: skipped.length,
|
|
379
|
+
invalid,
|
|
380
|
+
},
|
|
381
|
+
items,
|
|
382
|
+
skipped,
|
|
383
|
+
assistant,
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* 执行恢复:跑同一份计划,然后按计划写入。
|
|
389
|
+
*
|
|
390
|
+
* 只增不删——本机现有条目一条都不会因为这次恢复而消失。
|
|
391
|
+
*
|
|
392
|
+
* @returns {{ok: boolean, error?: string, added: number, skipped: number, invalid: number, assistant: boolean}}
|
|
393
|
+
*/
|
|
394
|
+
export function applyRestore(payload, { store, prefs }) {
|
|
395
|
+
const plan = planRestore(payload, { store, prefs });
|
|
396
|
+
if (!plan.ok) {
|
|
397
|
+
return {
|
|
398
|
+
ok: false,
|
|
399
|
+
error: plan.error,
|
|
400
|
+
added: 0,
|
|
401
|
+
skipped: 0,
|
|
402
|
+
invalid: 0,
|
|
403
|
+
assistant: false,
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
let added = 0;
|
|
407
|
+
if (store) {
|
|
408
|
+
for (const item of plan.items) {
|
|
409
|
+
try {
|
|
410
|
+
store.add({
|
|
411
|
+
scope: item.scope,
|
|
412
|
+
text: item.text,
|
|
413
|
+
source: item.source,
|
|
414
|
+
origin: item.origin,
|
|
415
|
+
pinned: item.pinned,
|
|
416
|
+
});
|
|
417
|
+
added += 1;
|
|
418
|
+
} catch (err) {
|
|
419
|
+
// 单条失败不该中断整次恢复:脱敏后为空、库写满都会走到这里。
|
|
420
|
+
plan.skipped.push({ index: -1, reason: err?.message ?? "写入失败" });
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
let assistant = false;
|
|
425
|
+
if (plan.assistant && prefs?.set) {
|
|
426
|
+
try {
|
|
427
|
+
prefs.set(plan.assistant);
|
|
428
|
+
assistant = true;
|
|
429
|
+
} catch {
|
|
430
|
+
// 人格恢复失败不影响记忆:两块分别报告,不混成一个"失败"。
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
return {
|
|
434
|
+
ok: true,
|
|
435
|
+
added,
|
|
436
|
+
// 计划里的跳过 + 写入时失败的
|
|
437
|
+
skipped: plan.skipped.length,
|
|
438
|
+
invalid: plan.counts.invalid,
|
|
439
|
+
assistant,
|
|
440
|
+
};
|
|
441
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Break reminder (T-15; plan §5.7, decision D10). Work framing only: it says how long you
|
|
3
|
+
* have been working and nothing else. No streaks, no guilt, nothing caused by absence.
|
|
4
|
+
*
|
|
5
|
+
* What counts as activity is decided by the caller and fed in through `activity()`: in the
|
|
6
|
+
* plugin that is activity *from a person* (a message the user typed in any DSH client, see
|
|
7
|
+
* `isUserActivityEvent`, and a write request from the phone), not the agent's own output or
|
|
8
|
+
* injected messages, so an unattended run does not count.
|
|
9
|
+
*
|
|
10
|
+
* Rules:
|
|
11
|
+
* - a gap of `idleResetMs` (10 min) or more between activities starts the count again;
|
|
12
|
+
* - after `afterMs` (2 h) of continuous activity, `check()` reminds once and the count
|
|
13
|
+
* starts again, so the next reminder needs another full stretch;
|
|
14
|
+
* - at most one reminder per `minIntervalMs` (2 h), whatever happens to the count;
|
|
15
|
+
* - never while `isQuiet(date)` says quiet hours; never while `isEnabled()` is false.
|
|
16
|
+
*
|
|
17
|
+
* Pure state plus an injected clock, so every rule can be tested with a fake one. Nothing is
|
|
18
|
+
* written to disk: after a restart the count starts again, which can only delay a reminder.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Whether a session event is a person typing (T-15 review follow-up). Only `user/message`
|
|
23
|
+
* events whose source is `"user"` count (the kernel marks system injections with `plugin`,
|
|
24
|
+
* `tool`, `model`, `agent-instructions` and so on, in `data.source` or `data.message.source`),
|
|
25
|
+
* and never in a subagent session. Otherwise an unattended tool loop that injects messages
|
|
26
|
+
* would keep the count going and the user would be told they worked 2 h while away.
|
|
27
|
+
*/
|
|
28
|
+
export function isUserActivityEvent(session, event) {
|
|
29
|
+
if (event?.type !== "user/message") return false;
|
|
30
|
+
if (session?.header?.origin === "subagent") return false;
|
|
31
|
+
const kind = event?.data?.source?.kind ?? event?.data?.message?.source?.kind;
|
|
32
|
+
return kind === "user";
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const BREAK_AFTER_MS = 2 * 60 * 60_000;
|
|
36
|
+
export const BREAK_IDLE_RESET_MS = 10 * 60_000;
|
|
37
|
+
export const BREAK_MIN_INTERVAL_MS = 2 * 60 * 60_000;
|
|
38
|
+
/** How often the plugin calls `check()`. Minute precision is plenty for a 2-hour rule. */
|
|
39
|
+
export const BREAK_CHECK_MS = 60_000;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @param {object} [e]
|
|
43
|
+
* @param {() => number} [e.now] clock in ms (tests inject a fake one)
|
|
44
|
+
* @param {() => boolean} [e.isEnabled] the off switches (config and the app's setting)
|
|
45
|
+
* @param {(at: Date) => boolean} [e.isQuiet] quiet hours, in local time
|
|
46
|
+
* @param {(r: {at: number, workedMs: number}) => void} [e.remind] deliver one reminder
|
|
47
|
+
* @param {number} [e.afterMs]
|
|
48
|
+
* @param {number} [e.idleResetMs]
|
|
49
|
+
* @param {number} [e.minIntervalMs]
|
|
50
|
+
*/
|
|
51
|
+
export function createBreakReminder({
|
|
52
|
+
now = () => Date.now(),
|
|
53
|
+
isEnabled = () => true,
|
|
54
|
+
isQuiet = () => false,
|
|
55
|
+
remind = () => {},
|
|
56
|
+
afterMs = BREAK_AFTER_MS,
|
|
57
|
+
idleResetMs = BREAK_IDLE_RESET_MS,
|
|
58
|
+
minIntervalMs = BREAK_MIN_INTERVAL_MS,
|
|
59
|
+
} = {}) {
|
|
60
|
+
/** Start of the current continuous stretch, or null when there is none. */
|
|
61
|
+
let streakStart = null;
|
|
62
|
+
let lastActivityAt = null;
|
|
63
|
+
let lastRemindedAt = null;
|
|
64
|
+
let lastReason = "no-activity";
|
|
65
|
+
let timer = null;
|
|
66
|
+
|
|
67
|
+
const reset = () => {
|
|
68
|
+
streakStart = null;
|
|
69
|
+
lastActivityAt = null;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
/** Record one piece of client activity. */
|
|
73
|
+
function activity(at = now()) {
|
|
74
|
+
// A long gap, or the clock moving backwards, starts a new stretch.
|
|
75
|
+
if (lastActivityAt === null || at < lastActivityAt || at - lastActivityAt >= idleResetMs) streakStart = at;
|
|
76
|
+
lastActivityAt = at;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Decide whether to remind now. Returns `{ fired, reason, workedMs? }`. */
|
|
80
|
+
function check(at = now()) {
|
|
81
|
+
const result = (() => {
|
|
82
|
+
if (streakStart === null) return { fired: false, reason: "no-activity" };
|
|
83
|
+
if (at < lastActivityAt) {
|
|
84
|
+
reset();
|
|
85
|
+
return { fired: false, reason: "clock-moved-back" };
|
|
86
|
+
}
|
|
87
|
+
if (at - lastActivityAt >= idleResetMs) {
|
|
88
|
+
reset();
|
|
89
|
+
return { fired: false, reason: "idle-reset" };
|
|
90
|
+
}
|
|
91
|
+
// Switched off: keep counting, so switching it back on behaves as if it had been on.
|
|
92
|
+
if (!isEnabled()) return { fired: false, reason: "disabled" };
|
|
93
|
+
const workedMs = at - streakStart;
|
|
94
|
+
if (workedMs < afterMs) return { fired: false, reason: "not-yet" };
|
|
95
|
+
if (lastRemindedAt !== null && at >= lastRemindedAt && at - lastRemindedAt < minIntervalMs) {
|
|
96
|
+
return { fired: false, reason: "min-interval" };
|
|
97
|
+
}
|
|
98
|
+
if (isQuiet(new Date(at))) return { fired: false, reason: "quiet-hours" };
|
|
99
|
+
lastRemindedAt = at;
|
|
100
|
+
streakStart = at;
|
|
101
|
+
remind({ at, workedMs });
|
|
102
|
+
return { fired: true, reason: "sent", workedMs };
|
|
103
|
+
})();
|
|
104
|
+
lastReason = result.reason;
|
|
105
|
+
return result;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function start(intervalMs = BREAK_CHECK_MS) {
|
|
109
|
+
if (timer) return;
|
|
110
|
+
timer = setInterval(() => {
|
|
111
|
+
try {
|
|
112
|
+
check();
|
|
113
|
+
} catch {
|
|
114
|
+
// A failing delivery must not stop the timer; the next check tries again later.
|
|
115
|
+
}
|
|
116
|
+
}, intervalMs);
|
|
117
|
+
timer.unref?.();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function stop() {
|
|
121
|
+
if (timer) clearInterval(timer);
|
|
122
|
+
timer = null;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return {
|
|
126
|
+
activity,
|
|
127
|
+
check,
|
|
128
|
+
start,
|
|
129
|
+
stop,
|
|
130
|
+
/** Read-only state for diagnostics and tests. */
|
|
131
|
+
snapshot: () => ({ streakStart, lastActivityAt, lastRemindedAt, lastReason, running: timer !== null }),
|
|
132
|
+
};
|
|
133
|
+
}
|