@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
package/lib/index.js CHANGED
@@ -5,11 +5,12 @@
5
5
  * 发消息(agent.followup / steer)、看进度与收通知(session/event + agent/status
6
6
  * 事件桥 → SSE)、会话历史、二维码。
7
7
  *
8
- * 设计依据见 docs/01-PRD.md ~ docs/04-security.md。
8
+ * 设计依据见 docs/CONSOLIDATED-DOCUMENTATION.en.md Part 01 ~ Part 04。
9
9
  */
10
+ import { protocolInfo } from "./protocol.js";
10
11
  import { networkInterfaces, hostname } from "node:os";
11
12
  import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
12
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, statSync, createReadStream } from "node:fs";
13
+ import { closeSync, constants as fsConstants, existsSync, fstatSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync, writeSync, statSync, createReadStream } from "node:fs";
13
14
  import { readdir } from "node:fs/promises";
14
15
  import { join, sep, resolve, basename } from "node:path";
15
16
  import { createServer as createHttpServer, request as httpRequest } from "node:http";
@@ -22,30 +23,46 @@ import { scopeTarget } from "@deepseek-ai/dsh-scope";
22
23
  import { createTitleCache } from "./session-title-cache.js";
23
24
  import { createSessionTitleRefresher, DEFAULT_TITLE_REFRESH_BUDGET_MS, DEFAULT_TITLE_REFRESH_CONCURRENCY } from "./session-title-refresh.js";
24
25
  export { normalizeCodexUsage, normalizeDeepSeekBalance, normalizeOpenCodeUsage, usageWindowLabel } from "./account-usage.js";
26
+ import { createMemoryRoutes } from "./memory/routes.js";
27
+ import { openMemoryStore, wipeMemoryFiles } from "./memory/store.js";
28
+ import { isProtectedFile, isProtectedPath, realPathOf } from "./protected-paths.js";
29
+ import { extractMemories, recordMemories } from "./memory/extract.js";
30
+ import { createMemoryContextProvider, installMemoryContext, MEMORY_CONTEXT_NAME } from "./memory/context.js";
31
+ import { createAssistantPrefs, modeBrief } from "./assistant-prefs.js";
32
+ import { activePersonaCard, createPersonaCardStore, createPersonaRoutes, personaPromptText } from "./persona-cards.js";
25
33
  import { createGitReadService } from "./git-read-service.js";
26
34
  import { createLoginRateLimiter } from "./rate-limit.js";
27
- import { RPC_ENDPOINT_RENAMES, RPC_PAYLOAD_ADAPTER, RPC_STREAM_METHODS, projectionOf, rpcError } from "./rpc-adapter.js";
35
+ import { RPC_ENDPOINT_RENAMES, RPC_PAYLOAD_ADAPTER, RPC_STREAM_METHODS, isEndpointUnavailable, projectionOf, rpcError } from "./rpc-adapter.js";
28
36
  import { guardRes, sendJson, sendError, readBody, requireGet, requirePost } from "./http-util.js";
29
- import { mobileRemoteStateDir, resolveAuthToken, resolveLanBridgeEnabled, resolveLanBridgePort, formatConnectionBanner } from "./auto-config.js";
30
- import { loadOrCreateIdentity } from "./relay/identity.js";
37
+ import { AUTO as AUTO_TOKEN, effectiveAuthSetting, mobileRemoteStateDir, resolveAuthToken, resolveLanBridgeEnabled, resolveLanBridgePort, rotateAuthToken, formatConnectionBanner } from "./auto-config.js";
38
+ import { RETIRED_ROOM_MS, loadOrCreateIdentity, loadRetiredIdentities, retireIdentity, rotateIdentity } from "./relay/identity.js";
31
39
  import { DeviceStore } from "./relay/devices.js";
32
40
  import { RelayConnector } from "./relay/connector.js";
41
+ import { createRelayDemand } from "./relay/on-demand.js";
33
42
  import { createHttpReplayer } from "./relay/serve.js";
34
43
  import { buildPairingUri, isAllowedRelayUrl } from "./relay/pairing.js";
44
+ import { pairingFingerprint as pairingFingerprintOf } from "./relay/fingerprint.js";
35
45
  import { b64u as relayB64u } from "./relay/crypto.js";
36
46
 
37
47
  export { Config, DEFAULT_ENUMERATION_BUDGET_MS, DEFAULT_WARM_UP_TITLE_BUDGET_MS } from "./config.js";
38
48
  import { DEFAULT_ENUMERATION_BUDGET_MS, DEFAULT_WARM_UP_TITLE_BUDGET_MS } from "./config.js";
39
- import { deriveKeyRef, queryAccountUsage } from "./account-usage-query.js";
49
+ import { deriveKeyRef, queryAccountUsage, queryDeepSeekAccountBalance } from "./account-usage-query.js";
40
50
  import { FILE_RANGE_CAPABILITIES, clampText, ifNoneMatch, parseByteRange, fileMimeOf, mapBounded, normalizeServerPath, orderQrAddresses, pruneReceiptMap, receiptExpired, redactPathText, requestAbort, requestHeaderText, validateQuestionAnswers } from "./api-helpers.js";
41
- import { capabilityState, hostPeerSource, jobsCallerFor, jobsNeedsSessionId, readSettingsSection, readSettingsSectionStrict, wireStreamTakesControl } from "./host-compat.js";
51
+ import { capabilityState, firstRootAgent, hostPeerSource, jobsCallerFor, jobsNeedsSessionId, readSettingsSection, readSettingsSectionStrict, wireStreamTakesControl } from "./host-compat.js";
42
52
  import { pushToChannel as deliverPush } from "./push.js";
53
+ import { createProactiveScheduler } from "./proactive.js";
54
+ import { CHATTING_MS, DEFAULT_IDLE_MS, isUserIdle, pickMaterial } from "./proactive-material.js";
55
+ import { createReminderRoutes, createReminderStore } from "./reminders.js";
56
+ import { createBreakReminder, isUserActivityEvent } from "./break-reminder.js";
57
+ import { MAX_RESTORE_BODY_BYTES, MIN_BACKUP_PASSPHRASE, applyRestore, buildBackup, decryptBackup, encryptBackup, isEncryptedBackup, planRestore } from "./backup.js";
58
+ import { buildRotation } from "./session-rotation.js";
59
+ import { inQuietHours, kindLabelOf, notifyBody, notifyHeadline, quietHoursSuppress, shouldSuppressForQuietHours } from "./notify-copy.js";
43
60
  import { compareSessionsForList, latestMessageTimeOf, planMessageTimePrune } from "./session-list.js";
44
- import { EVENT_TIMELINE_CAPABILITIES, detailEventFor, isDetailVisibleType, isLiveTimelineRecord, isTimelineRecord, isVisibleConversationMessage, sniffImageType, summarizeEvent } from "./timeline.js";
61
+ import { EVENT_TIMELINE_CAPABILITIES, blocksToText, detailEventFor, isDetailVisibleType, isLiveTimelineRecord, isTimelineRecord, isVisibleConversationMessage, sniffImageType, summarizeEvent } from "./timeline.js";
45
62
  import { EVENT_DETAIL_MAX_BYTES, SEEDED_PREFIX_ERROR_MESSAGE, TURN_OUTLINE_TIMEOUT_MS, classifyEventDetailReadError, classifyTurnOutlineReadError, createTurnOutlineQueue, raceWithDeadline, turnOutlineCapabilityOf, turnOutlineStateOf } from "./turn-outline.js";
46
63
  export { codexProxyUrl } from "./account-usage-query.js";
47
64
  export { classifyFetchFailure, normalizeServerPath, orderQrAddresses, pruneReceiptMap, receiptExpired, redactPathText, requestAbort, requestHeaderText, safeFailureReason, validateQuestionAnswers } from "./api-helpers.js";
48
- export { capabilityState, createInProcessPeer, hostPeerSource, jobsCallerFor, jobsNeedsSessionId, readSettingsSection, readSettingsSectionStrict, wireStreamTakesControl } from "./host-compat.js";
65
+ export { capabilityState, createInProcessPeer, firstRootAgent, hostPeerSource, jobsCallerFor, jobsNeedsSessionId, liveRootAgents, readSettingsSection, readSettingsSectionStrict, wireStreamTakesControl } from "./host-compat.js";
49
66
  export { ntfyPublish } from "./push.js";
50
67
  export { CORPUS_FRESH_MS, compareSessionsForList, latestMessageTimeOf, planMessageTimePrune, sessionListSortKey } from "./session-list.js";
51
68
  export { MESSAGE_EVENT_TYPES, blocksToText, detailEventFor, isDetailVisibleType, isLiveTimelineRecord, isMessageEventType, isTimelineRecord, isVisibleConversationMessage, summarizeEvent } from "./timeline.js";
@@ -60,27 +77,263 @@ export const inject = ["webServer"];
60
77
  /** 旧宿主逐个标题兜底的读取宽度:与宿主 `persistedReadConcurrency` 默认值一致(≤4)。 */
61
78
  const TITLE_FALLBACK_READ_WIDTH = DEFAULT_TITLE_REFRESH_CONCURRENCY;
62
79
 
80
+ /** 助手口吻上下文的贡献名。 */
81
+ const ASSISTANT_CONTEXT_NAME = "mobile-remote:assistant";
82
+
83
+ /**
84
+ * 把「现在用什么口吻、在什么模式」告诉模型。
85
+ *
86
+ * 为什么值得单独一段:人格只改通知文案的话,用户在 App 里切了人格、回到对话里
87
+ * 发现助手还是那个腔调——那这个开关就是假的。反过来,事实部分必须完全一致,
88
+ * 所以这里只写"怎么说",不写"说什么"。
89
+ *
90
+ * T-31 (D8): the persona part is the active persona card's own text, verbatim
91
+ * (personaPromptText); no fixed persona phrases are added. modeBrief stays: it is the
92
+ * work/life memory scope, not persona.
93
+ *
94
+ * @param {object} ctx 插件上下文
95
+ * @param {() => {mode: string}} getPrefs 每次装配时取当前值
96
+ * @param {() => object|null} getCard the active persona card
97
+ * @returns {boolean} 是否挂上(宿主没这个服务时为 false)
98
+ */
99
+ function installAssistantContext(ctx, getPrefs, getCard) {
100
+ const systemPrompt = ctx.get?.("systemPrompt");
101
+ if (!systemPrompt || typeof systemPrompt.context !== "function") return false;
102
+ systemPrompt.context({
103
+ name: ASSISTANT_CONTEXT_NAME,
104
+ // 排在记忆之后:先知道"它是谁",再决定"这些记忆为什么值得提"。
105
+ order: 70,
106
+ // T-31 fix: the card is user text; the host must not interpolate {{variables}} in it.
107
+ interpolate: false,
108
+ text: (assembly) => {
109
+ try {
110
+ const { mode } = getPrefs();
111
+ // A delegated subagent works for its parent; the user's persona card is not for it.
112
+ // (Best effort: the assembly scope is the agent when the host passes one.)
113
+ const subagent = assembly?.scope?.session?.header?.origin === "subagent";
114
+ const card = subagent ? "" : personaPromptText(getCard());
115
+ return card === "" ? modeBrief(mode) : `${card}\n${modeBrief(mode)}`;
116
+ } catch {
117
+ return "";
118
+ }
119
+ },
120
+ });
121
+ return true;
122
+ }
123
+
63
124
  export function apply(ctx, configInput) {
64
125
  // 零配置(v3.2.4):把 "@auto" 口令与 "auto" 开桥在这里**一次性**解析成真实值,
65
126
  // 之后整个函数(认证、qr-config、LAN 桥、诊断)看到的都是确定的 authToken / lanBridge.enabled。
66
- const tokenInfo = resolveAuthToken(configInput.authToken);
67
127
  const bridgeSetting = configInput.lanBridge?.enabled;
128
+ const lanBridgeResolved = resolveLanBridgeEnabled(bridgeSetting, {
129
+ webHost: ctx.webServer?.host,
130
+ webPort: ctx.webServer?.port,
131
+ bridgePort: configInput.lanBridge?.port ?? 3080,
132
+ });
133
+ // T-03 (E6): an empty authToken switches auth off only when nothing but this computer can
134
+ // reach the server; otherwise it is resolved exactly like "@auto".
135
+ const authSetting = effectiveAuthSetting(configInput.authToken, {
136
+ webHost: ctx.webServer?.host,
137
+ lanBridgeEnabled: lanBridgeResolved,
138
+ trustedHosts: configInput.trustedHosts,
139
+ relayEnabled: Boolean(configInput.relay?.enabled),
140
+ });
141
+ const tokenInfo = resolveAuthToken(authSetting);
142
+ if (authSetting === AUTO_TOKEN && configInput.authToken !== AUTO_TOKEN) {
143
+ ctx.logger.warn(
144
+ "mobile-remote: authToken is empty but this server is reachable from other devices (LAN, bridge, tunnel or relay), " +
145
+ "so a generated token is used instead / authToken 为空但服务可被其他设备访问,已改用自动生成的口令",
146
+ );
147
+ }
68
148
  const config = {
69
149
  ...configInput,
70
150
  authToken: tokenInfo.token,
71
151
  lanBridge: {
72
152
  ...configInput.lanBridge,
73
- enabled: resolveLanBridgeEnabled(bridgeSetting, {
74
- webHost: ctx.webServer?.host,
75
- webPort: ctx.webServer?.port,
76
- bridgePort: configInput.lanBridge?.port ?? 3080,
77
- }),
153
+ enabled: lanBridgeResolved,
78
154
  port: resolveLanBridgePort(bridgeSetting, configInput.lanBridge?.port ?? 3080, ctx.webServer?.port),
79
155
  },
80
156
  };
81
157
  const basePath = config.path;
82
158
  // 状态目录:与口令(auto-config)、中继身份同一个根,统一遵守 DSH_HOME(默认 ~/.dsh/mobile-remote)。
83
159
  const STATE_DIR = mobileRemoteStateDir();
160
+ // ── 长期记忆(v3.3.0,T7)─────────────────────────────────────────────
161
+ // 懒加载 + 默认关闭:配置没开时完全不碰磁盘,也不创建 memory.db。
162
+ // 打开后仍然只有本机文件,不经过任何服务器。
163
+ let memoryStore = null;
164
+ let memoryStoreFailed = null;
165
+ const getMemoryStore = () => {
166
+ if (!config.memory?.enabled) return null;
167
+ if (memoryStoreFailed) throw memoryStoreFailed;
168
+ if (memoryStore) return memoryStore;
169
+ try {
170
+ memoryStore = openMemoryStore({ dir: STATE_DIR });
171
+ } catch (err) {
172
+ // 记下失败原因而不是每请求重试:磁盘满/权限错时反复 open 只会更糟。
173
+ memoryStoreFailed = err;
174
+ ctx.logger.warn(`mobile-remote: 记忆库打不开(${err?.message ?? err})——记忆功能不可用,其它功能不受影响`);
175
+ throw memoryStoreFailed;
176
+ }
177
+ return memoryStore;
178
+ };
179
+ const handleReminders = createReminderRoutes({ store: () => reminderStore });
180
+ const handlePersona = createPersonaRoutes({ store: () => personaCards, prefs: () => assistantPrefs.get() });
181
+ const handleMemory = createMemoryRoutes({
182
+ store: getMemoryStore,
183
+ // T-63: "delete all memory" while memory is off (or the store failed to open) deletes the files.
184
+ wipe: () => (memoryStore ? 0 : wipeMemoryFiles(STATE_DIR)),
185
+ // T-63 fix: what the user said this turn waits in pendingUserText until turn/end, then gets
186
+ // extracted into memory. "Delete all" must drop it too, or it is written back after the wipe.
187
+ onDeleteAll: () => pendingUserText.clear(),
188
+ });
189
+ // ── 主动消息调度器(v3.4.0,P0-5/P0-6)──────────────────────────────
190
+ // 与推送的分工:推送是"任务状态变了,告诉你一声"(一定有事件);主动消息是
191
+ // "它自己挑时候开口"(可以没有事件)。后者必须有上限、安静时段与"别插嘴",
192
+ // 否则很快变成骚扰——用户第一件事就是永久关掉它,功能等于没做。
193
+ //
194
+ // 默认**关闭**(`config.proactive.enabled`):用户没答应过"你可以主动找我",
195
+ // 就不该在升级后突然开始收到消息。与记忆库同一个原则。
196
+ //
197
+ // `nextFireAt` 落盘、每次 tick 重算,而不是排一个长 setTimeout:进程重启、
198
+ // 笔记本合盖、系统时间跳变之后长定时器就永久失效,用户再也等不到这条提醒。
199
+ // T-32 activity state for the proactive gates (§5.7). Activity = what a person does: a message
200
+ // typed in any client (lastTypedAt too) or a phone write request. `returned` is set when the
201
+ // app reconnects after the user has been idle: the moment "task news when you return" is for.
202
+ let lastUserActivityAt = 0;
203
+ let lastTypedAt = 0;
204
+ // T-32 fix: `returned` is set only by the main app's foreground signal (POST /presence), never
205
+ // by an event-stream connect: the Android floating pet keeps its own stream and reconnects
206
+ // after network blips while the user is away. `newsCursor`: results up to here were reported.
207
+ let returned = null; // { at, since }
208
+ let newsCursor = 0;
209
+ const proactiveIdleMs = () => config.proactive?.activeWindowMs ?? DEFAULT_IDLE_MS;
210
+ /** Sessions whose agent is running (a reminder tied to one of them waits). */
211
+ const runningSessions = () => {
212
+ try {
213
+ return (ctx.get("agents")?.list?.() ?? [])
214
+ .filter((a) => a?.status === "running" || a?.status === "busy")
215
+ .map((a) => agentSessionId(a));
216
+ } catch {
217
+ return [];
218
+ }
219
+ };
220
+ const reminderStore = createReminderStore({ dir: STATE_DIR });
221
+ const proactive = createProactiveScheduler({
222
+ dir: STATE_DIR,
223
+ isQuiet: () =>
224
+ shouldSuppressForQuietHours({
225
+ kind: "reminder",
226
+ at: new Date(),
227
+ runtime: assistantPrefs.get().quietHours,
228
+ fallback: config.quietHours,
229
+ }),
230
+ // Gate: the user has been idle ≥ 30 min (never while chatting); see isUserIdle for the return window.
231
+ isUserActive: () =>
232
+ !isUserIdle({
233
+ now: new Date(),
234
+ lastActivityAt: lastUserActivityAt,
235
+ lastTypedAt,
236
+ returnedAt: returned?.at ?? null,
237
+ idleMs: proactiveIdleMs(),
238
+ }),
239
+ // Gate: no session is busy (an agent is running).
240
+ isBusy: () => runningSessions().length > 0,
241
+ // User-set reminders only wait while the user is chatting right now (T-32 fix).
242
+ isChatting: () => Date.now() - lastTypedAt < CHATTING_MS,
243
+ // Real things only (lib/proactive-material.js): due reminders, waiting approvals/questions,
244
+ // task news on return, a morning summary. Nothing caused by absence.
245
+ pick: async ({ level, now, sentKeys, dueOnly = false } = {}) => {
246
+ const pending = [];
247
+ for (const [key, frame] of pendingFrames) {
248
+ if (!frame || typeof frame !== "object") continue;
249
+ const approval = key.startsWith("a:");
250
+ pending.push({
251
+ key,
252
+ id: approval ? String(frame.approvalId ?? key.slice(2)) : String(frame.questionId ?? frame.rpcId ?? key.slice(2)),
253
+ sessionId: String(frame.sessionId ?? ""),
254
+ approval,
255
+ toolName: frame.toolName ?? null,
256
+ at: Number(frame.at),
257
+ });
258
+ }
259
+ const finished = [...notifStore.values()]
260
+ .filter((n) => n.kind === "completed" || n.kind === "failed")
261
+ .map((n) => ({ kind: n.kind, time: n.time, sessionId: n.sessionId }));
262
+ return pickMaterial({
263
+ now: now ?? new Date(),
264
+ level,
265
+ sentKeys,
266
+ reminders: reminderStore.list(),
267
+ pending,
268
+ finished,
269
+ returned,
270
+ quietEnd: assistantPrefs.get().quietHours?.end,
271
+ dueOnly,
272
+ busySessions: runningSessions(),
273
+ });
274
+ },
275
+ deliver: async (item) => {
276
+ // With the app connected: into the notification center (mobile/notify), which the app
277
+ // shows. Without: the same push channels and wording layer as every other push
278
+ // (quiet hours, cooldown, redaction). Throw when nothing went out, so the scheduler
279
+ // does not count it (see pushSend).
280
+ if (connections.size > 0) {
281
+ await pushNotification(item.sessionId ?? "", "reminder", item.text, item.sessionId ? {} : { fixedTitle: item.title });
282
+ } else {
283
+ const ok = await pushSend("reminder", item.sessionId ?? "", item.title ?? "", item.text);
284
+ if (!ok) throw new Error("no-push-channel");
285
+ }
286
+ // T-32 fix: results reported once are not news again on the next return.
287
+ if (item.kind === "news" && Number.isFinite(item.until)) {
288
+ newsCursor = Math.max(newsCursor, item.until);
289
+ returned = null;
290
+ }
291
+ },
292
+ log: ({ reason, at }) => {
293
+ // 只记判据与时刻,不记候选内容——日志也会被导出。
294
+ ctx.logger.info?.(`mobile-remote: 主动消息 ${reason}(${at})`);
295
+ },
296
+ config: {
297
+ enabled: config.proactive?.enabled === true,
298
+ dailyLimit: config.proactive?.dailyLimit,
299
+ minGapMs: config.proactive?.minGapMs,
300
+ tickMs: config.proactive?.tickMs,
301
+ },
302
+ });
303
+ // 注意:这里**只创建不启动**。`start()` 会立刻跑一次 tick,而 tick 要用到
304
+ // `assistantPrefs` / `pendingFrames` / `pushSend`——它们都定义在下面。
305
+ // 启动放在它们全部就位之后(见 `proactive.start()` 的注释)。
306
+ // 模式与人格必须同时作用在两处:通知措辞(下面 pushSend 已用 config.persona)
307
+ // 与 agent 对话上下文(这里注册)。只写手机本地的话,电脑上的助手毫不知情。
308
+ const assistantPrefs = createAssistantPrefs({
309
+ dir: STATE_DIR,
310
+ // quietHours from the config is the documented fallback (runtime prefs → config → 23:30–08:30).
311
+ // Without it here, prefs always answered the hard default and a configured window was ignored.
312
+ defaults: () => ({ mode: config.mode ?? "work", persona: config.persona ?? "colleague", quietHours: config.quietHours }),
313
+ });
314
+ // 记忆 → agent 上下文(T7 的「能召回」)。只登记一次,provider 每次装配时才读库:
315
+ // 这样记忆在对话中途被改/删,下一轮就生效,不需要重载插件。
316
+ // 宿主没有 systemPrompt 服务时静默降级(记忆只能存、读不到),不影响其它功能。
317
+ const memoryContextInstalled = installMemoryContext(
318
+ ctx,
319
+ createMemoryContextProvider({
320
+ // 直接给 getMemoryStore:功能没开时它返回 null,库坏了时它抛出(原因已由
321
+ // getMemoryStore 记过一次日志)。两种"没有记忆"由 provider 统一降级成空串,
322
+ // 但不在这里吞掉——吞掉之后就分不出「没开」和「坏了」。
323
+ getStore: getMemoryStore,
324
+ getMode: () => assistantPrefs.get().mode,
325
+ }),
326
+ );
327
+ if (config.memory?.enabled && !memoryContextInstalled) {
328
+ // 库有了、接口有了,但宿主没提供 systemPrompt:agent 读不到记忆。
329
+ // 这时候「记忆功能开着」是句假话,明确说出来,别让人以为它在工作。
330
+ ctx.logger.warn(
331
+ "mobile-remote: 宿主没有 systemPrompt 服务,长期记忆只能存、不会进入对话上下文",
332
+ );
333
+ }
334
+ // 人格与模式 → 对话上下文。与记忆分开注册:它们不依赖记忆库,关掉记忆也该生效。
335
+ const personaCards = createPersonaCardStore({ dir: STATE_DIR });
336
+ installAssistantContext(ctx, () => assistantPrefs.get(), () => activePersonaCard(personaCards, assistantPrefs.get()));
84
337
  const gitRead = createGitReadService(ctx, {
85
338
  onChanged: (repositoryId, changeKind = "refs") => broadcast({ type: "git/changed", repositoryId, changeKind }),
86
339
  });
@@ -125,15 +378,21 @@ export function apply(ctx, configInput) {
125
378
  // 连接在第一条响应结束后仍活着,旧写法会把它从集合里漏掉,卸载时就销毁不到。
126
379
  const lanBridgeTracked = new WeakSet();
127
380
  if (!authEnabled) {
381
+ // T-03: authEnabled is false only when nothing but this computer can reach the server (loopback
382
+ // webserver, no LAN bridge, no relay, no trustedHosts), so this is not an exposure warning: it says
383
+ // why a phone cannot connect and how to change that. Other devices get 401 (see the auth gate below).
128
384
  ctx.logger.warn(
129
- "mobile-remote: 访问口令(authToken)未启用——同一网络内任何设备都能连接并控制 agent,建议立即配置强口令(见 docs/04-security.md)"
385
+ "mobile-remote: authToken 为空,且服务只有本机可达(没有 LAN 桥、中继和 trustedHosts):只接受本机请求,其他设备会收到 401,手机目前连不上。" +
386
+ "要让手机连接,请删掉空的 authToken(沿用默认的 \"@auto\" 会自动生成口令),或打开 lanBridge / relay(见 docs/USER-GUIDE.zh-CN.md「安全须知」)" +
387
+ " / authToken is empty and only this computer can reach the server: other devices get 401 and phones cannot connect yet." +
388
+ " Remove the empty authToken (the default \"@auto\" generates one) or enable lanBridge / relay to connect a phone",
130
389
  );
131
390
  } else if (config.authToken.length < 16) {
132
391
  // v2.9.0 review(B6):弱口令告警(仅警告不阻断,避免既有用户升级即断)
133
392
  ctx.logger.warn("mobile-remote: authToken 短于 16 字符,建议更换为 ≥16 字符强随机口令");
134
393
  }
135
394
 
136
- // ── 移动端动作注册表服务(插件契约 v0.1,docs/03-api.md §6.8) ──
395
+ // ── 移动端动作注册表服务(插件契约 v0.1,docs/CONSOLIDATED-DOCUMENTATION.en.md Part 03 §6.8) ──
137
396
  const actionEntries = new Map();
138
397
  const mobileActions = {
139
398
  register(spec) {
@@ -976,13 +1235,15 @@ export function apply(ctx, configInput) {
976
1235
  }
977
1236
  return undefined;
978
1237
  };
979
- const pushNotification = async (sessionId, kind, detail) => {
1238
+ // `fixedTitle` (T-15): a notification that belongs to no session (sessionId "") brings its own
1239
+ // title; there is no session title to look up or wait for.
1240
+ const pushNotification = async (sessionId, kind, detail, { fixedTitle } = {}) => {
980
1241
  const sessions = ctx.get("sessions");
981
1242
  let session = sessions?.get(sessionId);
982
- let title = notifyTitle(sessionId, session);
1243
+ let title = fixedTitle ?? notifyTitle(sessionId, session);
983
1244
  // v3.1.2(悬浮球反馈):会话标题由 LLM 异步生成,常晚于「任务完成」通知几秒才落地——
984
1245
  // 等一小段再读一次,避免通知显示会话短码而非名称。
985
- if (title === shortSessionId(sessionId)) {
1246
+ if (fixedTitle === undefined && title === shortSessionId(sessionId)) {
986
1247
  await new Promise((resolve) => setTimeout(resolve, 4000));
987
1248
  session = sessions?.get(sessionId);
988
1249
  title = notifyTitle(sessionId, session);
@@ -1012,24 +1273,66 @@ export function apply(ctx, configInput) {
1012
1273
  // v2.6.0 推送脱敏:minimal(默认)只推事件类型 + 会话短码,核心内容不进第三方通道;
1013
1274
  // standard 恢复旧行为(会话标题 + 事件详情),仅信任通道时开启。
1014
1275
  const pushMinimal = config.pushContent !== "standard";
1276
+ // 返回 boolean:**是否真的交给了至少一个通道**。
1277
+ //
1278
+ // 为什么需要这个返回值:主动消息调度器要按「真的发出去了」才记账。没有通道时
1279
+ // 这里只能直接返回——如果让它看起来像成功,用户什么都没收到,配额却被扣了,
1280
+ // 那条提醒还会被永久标记为已发(`sentKeys`),等于永久丢掉一次提醒。
1015
1281
  const pushSend = async (kind, sessionId, title, detail) => {
1016
- if (config.pushUrls.length === 0) return;
1282
+ if (config.pushUrls.length === 0) return false;
1017
1283
  const key = `${sessionId}:${kind}`;
1018
1284
  const now = Date.now();
1019
1285
  const last = pushCooldowns.get(key) ?? 0;
1020
- if (now - last < config.pushCooldownMs) return; // 节流
1286
+ if (now - last < config.pushCooldownMs) return false; // 节流
1021
1287
  pushCooldowns.set(key, now);
1022
- const kindLabel = { completed: "✅ 任务完成", "needs-answer": "⚠ 需要你回答", failed: "❌ 任务失败" }[kind] ?? kind;
1288
+ // 后面还有几处 `return;`(安静时段、非法时间)——它们同样意味着“没发出去”。
1289
+ // 统一改掉而不是让调用方去猜。
1290
+ const kindLabel = kindLabelOf(kind);
1023
1291
  const shortId = shortSessionId(sessionId);
1024
- const redactedTitle = pushMinimal ? shortId : title;
1025
- // v3.1.5 S8:standard 模式也要脱敏——detail 常是内核错误原文(turn/end 失败原因,
1026
- // 可达 120 字,含工作区绝对路径)。第三方通道(ntfy/Server酱/Bark/企微)是外送面,
1027
- // 原文只留在服务端日志;minimal(默认)本来就不带 detail。
1028
- const redactedDetail = pushMinimal ? "" : redactPathText(detail);
1292
+ // 安静时段(T12):完成与余额这两类不吵人;「等你回答」和「失败」照发——
1293
+ // 它们停在那里等人,憋到早上才算真的坏了。默认窗口 23:30–08:30。
1294
+ //
1295
+ // 取值顺序是**运行时偏好 → 部署配置 → 硬默认**:App 里改的时间必须在这里
1296
+ // 生效,否则用户在手机上设了 22:00,夜里照样按 23:30 被吵醒(这正是 T9/T10
1297
+ // 修过的同一类问题:写进了手机本地、没到电脑)。
1298
+ if (
1299
+ shouldSuppressForQuietHours({
1300
+ kind,
1301
+ at: new Date(),
1302
+ runtime: assistantPrefs.get().quietHours,
1303
+ fallback: config.quietHours,
1304
+ })
1305
+ ) {
1306
+ ctx.logger.info?.(`mobile-remote: 安静时段,跳过 ${kind} 推送(${sessionId})`);
1307
+ return false;
1308
+ }
1309
+ // 标题:minimal 模式只给会话短码(不把会话标题外送),
1310
+ // 否则用三段式润色过的角色口吻标题。detail 里可能含路径,标题不带它。
1311
+ const headline = notifyHeadline({
1312
+ kind,
1313
+ title: pushMinimal ? "" : title,
1314
+ shortId,
1315
+ });
1316
+ // 正文:三段式(做了什么 / 要你知道 / 下一步)。minimal 模式仍不带 detail——
1317
+ // 第三方通道是外送面,内核原文只留在服务端日志。
1318
+ const body = notifyBody({
1319
+ kind,
1320
+ title: "",
1321
+ detail: pushMinimal ? "" : redactPathText(detail),
1322
+ });
1323
+ // 兜底:极端情况下文案层返回空串,退回旧标签,绝不让通知变成空白一条。
1324
+ const safeHeadline = headline.trim() === "" ? kindLabel : headline;
1325
+ const redactedTitle = safeHeadline;
1326
+ const redactedDetail = body.trim() === "" ? redactPathText(detail) : body;
1327
+ let delivered = 0;
1029
1328
  for (const target of config.pushUrls) {
1329
+ // 通道协议不变:仍传 kindLabel 作为「事件类型」,只是标题/正文换成人话。
1030
1330
  const outcome = await pushTracked(target, kind, kindLabel, redactedTitle, redactedDetail, sessionId);
1031
1331
  if (!outcome.ok) ctx.logger.warn(`mobile-remote: push to "${target.name}" failed: ${outcome.error}`);
1332
+ else delivered += 1;
1032
1333
  }
1334
+ // 全部通道都失败时不谎报成功:主动消息的配额与 `sentKeys` 都按这个返回值记账。
1335
+ return delivered > 0;
1033
1336
  };
1034
1337
  // ── 真结束通知(v2.7.2)──────────────────────────────
1035
1338
  // 多轮大任务(goal 驱动/连续队列)每轮 turn/end 只暂存结果;agent 转 idle
@@ -1279,6 +1582,15 @@ export function apply(ctx, configInput) {
1279
1582
  const error = sendError;
1280
1583
  // v2.7.2 review(M7):请求体解析失败统一处理——超限透传 413,其余 400
1281
1584
  const bodyError = (err, res) => error(res, err?.status === 413 ? 413 : 400, err?.status === 413 ? "payload-too-large" : "bad-request");
1585
+ /** Replace a file's content through an already-checked descriptor (T-62 fix). */
1586
+ const writeFdFully = (fd, buf) => {
1587
+ ftruncateSync(fd, 0);
1588
+ let offset = 0;
1589
+ while (offset < buf.length) offset += writeSync(fd, buf, offset, buf.length - offset, offset);
1590
+ };
1591
+ /** T-62: a file route asked for the DSH home (keys, token, relay key, memory). */
1592
+ const protectedPathError = (res) =>
1593
+ error(res, 403, "path-protected", "这里存放 DSH 与插件的密钥和数据,不能从手机访问 / this folder holds DSH's and the plugin's keys and data; it cannot be opened from the phone");
1282
1594
  // Phase 1(S1):读请求体并解析 JSON;失败已响应(bodyError),返回 undefined 供调用点提前 return。
1283
1595
  // v3.0.0:接受可选 limit 参数并透传 readBody——/send(图片 base64 大 body)传入 64MB,
1284
1596
  // 其余端点保持默认 64KB。此前该参数被静默丢弃,图片 >64KB 即触发 req.destroy(),
@@ -1370,6 +1682,57 @@ export function apply(ctx, configInput) {
1370
1682
  };
1371
1683
  // ── 问询/审批桥(移动端弹窗):rpcId → frame 待答清单,App 重连时补发 ──
1372
1684
  const pendingFrames = new Map(); // `q:${rpcId}` / `a:${approvalId}` -> { rpcId, at, ...frame }
1685
+ // 主动调度器在这里启动,而不是靠写完配置就近启动:`start()` 会**立刻**跑一次 tick,
1686
+ // 而 tick 要读 `pushSend`(deliver)、`assistantPrefs`(安静时段/人格)、
1687
+ // `pendingFrames`(候选来源)。这三者都必须已初始化——否则就是 TDZ 报错,
1688
+ // 插件在加载阶段直接崩掉,而不是"主动消息不工作"这么轻。
1689
+ if (config.proactive?.enabled) proactive.start();
1690
+ // ── Break reminder (T-15, §5.7, D10) ──────────────────────────────
1691
+ // Counts activity from clients only: user messages from any DSH client (onSessionEvent) and
1692
+ // write requests from the phone (handleApi). The agent's own output does not count, so an
1693
+ // unattended run never triggers it. Two off switches: `breakReminder.enabled` in the config
1694
+ // (this PC) and `breakReminder` in the assistant prefs (the app's setting).
1695
+ const breakReminder = createBreakReminder({
1696
+ isEnabled: () => config.breakReminder?.enabled !== false && assistantPrefs.get().breakReminder !== false,
1697
+ isQuiet: (at) =>
1698
+ shouldSuppressForQuietHours({
1699
+ kind: "break",
1700
+ at,
1701
+ runtime: assistantPrefs.get().quietHours,
1702
+ fallback: config.quietHours,
1703
+ }),
1704
+ remind: ({ at, workedMs }) => {
1705
+ const phoneOnline = connections.size > 0;
1706
+ // Three ways out, so it is never lost:
1707
+ // - `break/reminder` frame: the pet stretches on it (T-29/T-40);
1708
+ // - a sessionless entry in the notification center (`mobile/notify`), which the app
1709
+ // already turns into a banner, and the Android service into a notification, even
1710
+ // while the socket looks connected but the app is in the background;
1711
+ // - a push through the configured channels when no app is connected at all.
1712
+ broadcast({ type: "break/reminder", at, workedMinutes: Math.floor(workedMs / 60_000) });
1713
+ void pushNotification("", "break", notifyBody({ kind: "break" }), { fixedTitle: notifyHeadline({ kind: "break" }) }).catch((err) => {
1714
+ ctx.logger.warn(`mobile-remote: break reminder notification failed: ${err?.message ?? err}`);
1715
+ });
1716
+ ctx.logger.info?.(`mobile-remote: break reminder after ${Math.floor(workedMs / 60_000)} min (phone ${phoneOnline ? "online" : "offline"})`);
1717
+ if (!phoneOnline) {
1718
+ void pushSend("break", "", "", "").catch((err) => {
1719
+ ctx.logger.warn(`mobile-remote: break reminder push failed: ${err?.message ?? err}`);
1720
+ });
1721
+ }
1722
+ },
1723
+ });
1724
+ breakReminder.start();
1725
+ /** A person did something (T-15, T-32). `typed`: a message typed in a DSH client. */
1726
+ const noteUserActivity = ({ typed = false } = {}) => {
1727
+ const t = Date.now();
1728
+ lastUserActivityAt = t;
1729
+ if (typed) lastTypedAt = t;
1730
+ breakReminder.activity();
1731
+ proactive.noteReaction();
1732
+ };
1733
+ // 本轮用户说的话,等 turn/end 时决定要不要记进长期记忆。
1734
+ // 只存最近一条:一轮里发多条时,最后一条才是这轮的结论句。
1735
+ const pendingUserText = new Map(); // sessionId -> text
1373
1736
  // v2.7.2 review(M3):上限 + TTL,防"永不回答的审批/提问帧"永久残留并在每次重连全量回放
1374
1737
  const PENDING_FRAMES_MAX = 200;
1375
1738
  const PENDING_FRAMES_TTL = 24 * 3600 * 1000;
@@ -1383,7 +1746,8 @@ export function apply(ctx, configInput) {
1383
1746
  pendingFrames.delete(oldest);
1384
1747
  }
1385
1748
  };
1386
- const connect = (res) => {
1749
+ /** `via`: how the stream authenticated ("token" or "relay"); token streams end when the token rotates (T-62 fix). */
1750
+ const connect = (res, via = "token") => {
1387
1751
  if (connections.size >= config.maxConnections) {
1388
1752
  res.writeHead(503, { "content-type": "application/json; charset=utf-8" });
1389
1753
  res.end(JSON.stringify({ error: "too-many-connections" }));
@@ -1391,6 +1755,7 @@ export function apply(ctx, configInput) {
1391
1755
  }
1392
1756
  // review:先挂清理监听再写头/回放——握手瞬间客户端断开时不会留下滞留连接
1393
1757
  //(此前 close/error 监听在写完后才挂,握手即断的死连接靠 25s 心跳兜底)
1758
+ res.dshVia = via;
1394
1759
  res.on("close", () => connections.delete(res));
1395
1760
  // 半开连接:客户端进程被杀/断网后 close 可能迟迟不来,error 事件立即清理僵尸
1396
1761
  res.on("error", () => connections.delete(res));
@@ -1400,7 +1765,7 @@ export function apply(ctx, configInput) {
1400
1765
  "connection": "keep-alive",
1401
1766
  });
1402
1767
  res.write(": connected\n\n");
1403
- res.write(`data: ${JSON.stringify({ type: "hello", serverTime: Date.now(), capabilities: { eventTimeline: EVENT_TIMELINE_CAPABILITIES, turnOutline: turnOutlineCapabilityOf(ctx), fileRange: FILE_RANGE_CAPABILITIES, hold: { version: 1, onlineMs: Math.max(0, Number(config.pendingTimeoutMs ?? 120_000) || 0), offlineMs: Math.max(0, Number(config.offlineHoldMs ?? 300_000) || 0) } } })}\n\n`);
1768
+ res.write(`data: ${JSON.stringify({ type: "hello", serverTime: Date.now(), ...protocolInfo(), capabilities: { eventTimeline: EVENT_TIMELINE_CAPABILITIES, turnOutline: turnOutlineCapabilityOf(ctx), fileRange: FILE_RANGE_CAPABILITIES, hold: { version: 1, onlineMs: Math.max(0, Number(config.pendingTimeoutMs ?? 120_000) || 0), offlineMs: Math.max(0, Number(config.offlineHoldMs ?? 300_000) || 0) } } })}\n\n`);
1404
1769
  connections.add(res);
1405
1770
  // 补发断线期间挂起的问询/审批(与 PC 端 GUI 连接时的 pending 回放一致;超 TTL 的僵尸帧先清掉)
1406
1771
  for (const [key, f] of pendingFrames) {
@@ -1438,6 +1803,54 @@ export function apply(ctx, configInput) {
1438
1803
  // v3.1.6(issue #14 / ADR 0013):最新消息时间——只认**用户可见的对话消息**,
1439
1804
  // 工具活动、生命周期、协议元数据、系统注入都不算。这是会话列表的新排序依据。
1440
1805
  if (isVisibleConversationMessage(event)) touchMessageTime(session.id, event.time);
1806
+ // 长期记忆写入(T7 的「会记住」那一半)。
1807
+ // 挂在 turn/end 而不是每条 user/message 上:一轮结束才是一句完整的话,
1808
+ // 中途的半句常常还带着没说完的限定语(「我比较喜欢…」后面接什么,决定了
1809
+ // 这条该不该记)。这里只做**规则提取**,不调模型——理由见 lib/memory/extract.js。
1810
+ if (event.type === "user/message") {
1811
+ try {
1812
+ pendingUserText.set(session.id, blocksToText(event.data?.message?.content));
1813
+ } catch {
1814
+ // 取不到正文就算了,不影响别的功能。
1815
+ }
1816
+ }
1817
+ // T-15/T-32: a message the user typed in any client is activity (break reminder, proactive
1818
+ // gates, silence decay); injected messages and subagent sessions are not (isUserActivityEvent).
1819
+ if (isUserActivityEvent(session, event)) noteUserActivity({ typed: true });
1820
+ if (event.type === "turn/end") {
1821
+ const said = pendingUserText.get(session.id);
1822
+ pendingUserText.delete(session.id);
1823
+ // 记忆默认关闭:没开时这里一次都不该碰库(getMemoryStore 会返回 null)。
1824
+ if (said && config.memory?.enabled) {
1825
+ try {
1826
+ const store = getMemoryStore();
1827
+ if (store) {
1828
+ const candidates = extractMemories({
1829
+ text: said,
1830
+ mode: assistantPrefs.get().mode,
1831
+ });
1832
+ if (candidates.length > 0) {
1833
+ const written = recordMemories({
1834
+ store,
1835
+ candidates,
1836
+ meta: {
1837
+ sessionId: session.id,
1838
+ // 来源写成会话标题:用户能看懂「这条是从哪次对话来的」。
1839
+ origin: session.header?.title ?? null,
1840
+ },
1841
+ });
1842
+ if (written > 0) {
1843
+ ctx.logger.info?.(`mobile-remote: 记住了 ${written} 条(会话 ${shortSessionId(session.id)})`);
1844
+ broadcast({ type: "memory/changed" });
1845
+ }
1846
+ }
1847
+ }
1848
+ } catch (err) {
1849
+ // 记忆写不进去绝不能影响对话本身——它是附加能力,不是主链路。
1850
+ ctx.logger.warn(`mobile-remote: 记忆写入失败:${err?.message ?? err}`);
1851
+ }
1852
+ }
1853
+ }
1441
1854
  // 上下文窗口:request/context 事件携带模型上下文大小(PC 端圆环同源数据)
1442
1855
  if (event.type === "request/context" && Number.isInteger(event.data?.contextWindow)) {
1443
1856
  contextWindowMap.set(session.id, event.data.contextWindow);
@@ -1688,7 +2101,7 @@ export function apply(ctx, configInput) {
1688
2101
  * ④ 不是浏览器跨站请求(Sec-Fetch-Site)、Origin/Referer(若有)也是回环主机;
1689
2102
  * ⑤ 已配置 `trustedHosts`(中继形态)时默认整体关闭(`qrConfigBehindRelay`)。
1690
2103
  * 剩余风险:②③ 能被「裸 TCP 隧道里的攻击者」自己伪造(头是他写的),所以 ⑤ 才是兜底;
1691
- * 推荐拓扑是让隧道/反代指向 LAN 桥端口——桥永远不转发这些端点(见 docs/04-security.md §3b)。
2104
+ * 推荐拓扑是让隧道/反代指向 LAN 桥端口——桥永远不转发这些端点(见 docs/CONSOLIDATED-DOCUMENTATION.en.md Part 04 §3b)。
1692
2105
  */
1693
2106
  const localDesktopGate = (req, { relayGuard = true } = {}) => {
1694
2107
  const socketPeer = String(req.socket?.remoteAddress ?? "");
@@ -1726,8 +2139,8 @@ export function apply(ctx, configInput) {
1726
2139
  }
1727
2140
  return { ok: true };
1728
2141
  };
1729
- /** 首个 root agent(无 root 时退回任意 agent)。 */
1730
- const firstAgent = (agents) => agents?.roots()[0] ?? agents?.list()[0];
2142
+ /** 首个 root agent(无 root 时退回任意 agent)。T-01: roots() is gone from DSH 0.2.2-rc.2, see firstRootAgent. */
2143
+ const firstAgent = (agents) => firstRootAgent(agents) ?? (typeof agents?.list === "function" ? agents.list()[0] : undefined);
1731
2144
  /** 会话短码(统一格式:前 8 + … + 后 4;短 id 原样)。 */
1732
2145
  const shortSessionId = (id) => (id.length > 12 ? `${id.slice(0, 8)}…${id.slice(-4)}` : id);
1733
2146
  /** 通知标题:会话标题兜底短码。 */
@@ -2045,13 +2458,21 @@ export function apply(ctx, configInput) {
2045
2458
  return;
2046
2459
  }
2047
2460
  rateReset(ip);
2461
+ } else {
2462
+ // T-03 (E6): auth is off only when the server is loopback-only (effectiveAuthSetting),
2463
+ // so anything that is not plainly this computer means that assumption broke: another
2464
+ // device, a tunnel or reverse proxy (ngrok/cloudflared/Caddy arrive from 127.0.0.1 but
2465
+ // add forwarding headers or keep a public Host), a cross-site page. Same checks as the
2466
+ // desktop-only endpoints. Fail closed instead of serving it without a token.
2467
+ const local = localDesktopGate(req, { relayGuard: false });
2468
+ if (!local.ok) {
2469
+ error(res, 401, "auth-required", `访问口令未启用,只接受本机请求 / authentication is off, so only this computer may connect (${local.detail})`);
2470
+ return;
2471
+ }
2048
2472
  }
2049
- // authToken 为空(认证未启用)→ 此处**有意不设口令闸门**:这是 docs/04-security.md §2.1
2050
- // 记录的默认姿态(未配 0.0.0.0 时随 webserver 只听回环,靠 Host 白名单兜底),
2051
- // 不是遗漏。v3.1.5 前这里是 `else if (!authorized(req)) { 401 "认证未启用" }`,
2052
- // 而 authorized() 在 authEnabled=false 时恒为 true —— 那条分支永远不可达(死代码),
2053
- // 容易被误读成"未启用就拒绝一切"。真正的补强是上面的跨站校验;若要收紧到
2054
- // "未配置口令则拒绝启动/拒绝服务",那是启动策略变更(与既有部署契约冲突),另行决策。
2473
+ // T-15: an authenticated write from the phone is client activity for the break reminder.
2474
+ // Reads are left out: the app polls and reconnects in the background on its own.
2475
+ if ((method !== "GET" && method !== "HEAD") && rest !== "/presence") noteUserActivity();
2055
2476
  }
2056
2477
 
2057
2478
  if (rest === "/bootstrap") {
@@ -2088,6 +2509,8 @@ export function apply(ctx, configInput) {
2088
2509
  auth: { enabled: authEnabled },
2089
2510
  server: { port: ctx.webServer.port, urls, path: basePath },
2090
2511
  plugin: { name: "dsh-mobile-remote", version: pluginVersion() },
2512
+ // T-61: protocol range, optional features and the oldest app it works with.
2513
+ ...protocolInfo(),
2091
2514
  capabilities: {
2092
2515
  eventTimeline: EVENT_TIMELINE_CAPABILITIES,
2093
2516
  // 宿主是否**真的**挂了 `turnOutline` 投影单元、且观察接口可用,决定声明是
@@ -2108,6 +2531,215 @@ export function apply(ctx, configInput) {
2108
2531
  return;
2109
2532
  }
2110
2533
 
2534
+ // Persona cards (T-31): list, import (the app gates import on its entitlement), delete.
2535
+ if (rest === "/persona" || rest.startsWith("/persona/")) {
2536
+ if (await handlePersona(req, res, rest, method)) return;
2537
+ }
2538
+
2539
+ // The main app came to the foreground (T-32 fix): the only signal for "the user returned".
2540
+ // The floating pet's event stream never sends it. `awayMs`: how long the app was in the
2541
+ // background (absent after a cold start). A return needs the app away ≥ the idle window and
2542
+ // no message typed in any client meanwhile; news is what finished since the later of the
2543
+ // last typed message, the app going to the background, and the last news already sent.
2544
+ if (rest === "/presence") {
2545
+ if (requirePost(method, res)) return;
2546
+ const body = await readJson(req, res);
2547
+ if (body === undefined) return;
2548
+ if (body?.state !== "foreground") return error(res, 400, "bad-request", "state must be \"foreground\"");
2549
+ const t = Date.now();
2550
+ const idleMs = proactiveIdleMs();
2551
+ const awayMs = Number.isFinite(body.awayMs) && body.awayMs >= 0 ? body.awayMs : null;
2552
+ const wasAway = (awayMs === null || awayMs >= idleMs) && t - lastTypedAt >= idleMs;
2553
+ if (wasAway) {
2554
+ returned = { at: t, since: Math.max(lastTypedAt, awayMs === null ? 0 : t - awayMs, newsCursor) };
2555
+ if (config.proactive?.enabled) setImmediate(() => void proactive.tick());
2556
+ }
2557
+ noteUserActivity(); // opening the app is a reaction (silence decay)
2558
+ sendJson(res, 200, { ok: true, returned: wasAway });
2559
+ return;
2560
+ }
2561
+
2562
+ // Reminders (T-32): the "coming due" material of proactive messages.
2563
+ if (rest === "/reminders" || rest.startsWith("/reminders/")) {
2564
+ if (await handleReminders(req, res, rest, method)) return;
2565
+ }
2566
+
2567
+ // 长期记忆(v3.3.0,T7):/api/memory 下的列表 / 检索 / 新增 / 编辑 / 删除 / 导出。
2568
+ if (rest === "/memory" || rest.startsWith("/memory/")) {
2569
+ await handleMemory(req, res, url, rest, method);
2570
+ return;
2571
+ }
2572
+
2573
+ // 助手偏好(v3.3.0,T9):读取 / 切换模式与人格。
2574
+ //
2575
+ // 为什么必须走服务端:模式决定 agent 能看到哪些记忆,人格决定它怎么说话——
2576
+ // 两件事都发生在电脑上。只写手机本地的话,切换只是换了一句提示,
2577
+ // 电脑上的助手毫不知情,用户回到对话里会发现"没变"。
2578
+ if (rest === "/assistant") {
2579
+ if (method === "GET") {
2580
+ sendJson(res, 200, { ok: true, ...assistantPrefs.get() });
2581
+ return;
2582
+ }
2583
+ if (method === "PATCH" || method === "POST") {
2584
+ let body;
2585
+ try {
2586
+ // readBody 返回的是原始字符串(见 http-util.js),这里必须自己 parse——
2587
+ // 直接当对象用会永远读到 undefined,于是非法值不被拦、正常值也写不进去。
2588
+ body = JSON.parse(await readBody(req));
2589
+ } catch {
2590
+ return error(res, 400, "bad-request", "请求体不是合法 JSON");
2591
+ }
2592
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
2593
+ return error(res, 400, "bad-request", "请求体必须是对象");
2594
+ }
2595
+ try {
2596
+ const next = assistantPrefs.set({
2597
+ mode: body.mode,
2598
+ persona: body.persona,
2599
+ // 只有请求里带了 quietHours 才改它——App 切换模式时不该顺手
2600
+ // 把用户设好的安静时段冲回默认。
2601
+ quietHours: body.quietHours,
2602
+ // T-15: the app's switch for the break reminder; absent = unchanged.
2603
+ breakReminder: body.breakReminder,
2604
+ // T-31: the active persona card; absent = unchanged.
2605
+ personaCard: body.personaCard,
2606
+ });
2607
+ sendJson(res, 200, { ok: true, ...next });
2608
+ } catch (err) {
2609
+ // 非法值要明说,不能静默保留旧值——用户会以为切换成功了。
2610
+ error(res, 400, "bad-request", err?.message ?? "invalid value");
2611
+ }
2612
+ return;
2613
+ }
2614
+ sendError(res, 405, "method-not-allowed");
2615
+ return;
2616
+ }
2617
+
2618
+ // 备份 / 恢复 / 预演恢复(v3.4.0,P1-16)。
2619
+ //
2620
+ // 两条语义要分清:
2621
+ // POST /api/backup/restore?dryRun=1 只算计划、不写库 —— 用户先看清会写什么
2622
+ // POST /api/backup/restore 执行同一份计划
2623
+ // 预演与真恢复共用 `planRestore()`(lib/backup.js),否则预演会说"将恢复 42 条"
2624
+ // 而实际只写进 40 条,那就成了一句安慰话。
2625
+ if (rest === "/backup") {
2626
+ // GET:明文备份。POST {passphrase}:同一份备份,用口令加密(T-63,可选)。
2627
+ // 口令放在请求体里,不放 URL:URL 会进日志与历史记录。
2628
+ let passphrase;
2629
+ if (method === "POST") {
2630
+ const body = await readJson(req, res);
2631
+ if (body === undefined) return;
2632
+ passphrase = body?.passphrase;
2633
+ if (typeof passphrase !== "string" || passphrase.length < MIN_BACKUP_PASSPHRASE) {
2634
+ return error(res, 400, "weak-passphrase", `口令至少 ${MIN_BACKUP_PASSPHRASE} 个字符 / the passphrase needs at least ${MIN_BACKUP_PASSPHRASE} characters`);
2635
+ }
2636
+ } else if (method !== "GET" && method !== "HEAD") {
2637
+ sendError(res, 405, "method-not-allowed");
2638
+ return;
2639
+ }
2640
+ // 「记忆没开」与「库打不开」必须分开:前者是用户的设置,后者是故障。
2641
+ // 都回 null 的话,备份会在故障时静默产出一份**不含记忆**的文件,
2642
+ // 用户存下来还以为是完整备份——比直接报错坏得多。
2643
+ let store = null;
2644
+ try {
2645
+ store = getMemoryStore();
2646
+ } catch (err) {
2647
+ return error(
2648
+ res,
2649
+ 503,
2650
+ "memory-unavailable",
2651
+ `记忆库打不开,无法生成完整备份:${err?.message ?? err}`,
2652
+ );
2653
+ }
2654
+ const backup = buildBackup({
2655
+ // 记忆没开(null)时仍可备份人格:两块独立,不该因为一个没开就整份不给。
2656
+ store,
2657
+ prefs: assistantPrefs,
2658
+ });
2659
+ sendJson(res, 200, passphrase === undefined ? backup : encryptBackup(backup, passphrase));
2660
+ return;
2661
+ }
2662
+ if (rest === "/backup/restore") {
2663
+ if (method !== "POST") {
2664
+ sendError(res, 405, "method-not-allowed");
2665
+ return;
2666
+ }
2667
+ // T-55 (E5): its own 32 MiB limit (the default is 64 KiB), and "too large" is told apart
2668
+ // from "not JSON". The 413 goes out at once, before the body is read (declared length) or
2669
+ // as soon as it overflows (streamed). It is sent keep-alive on purpose: Node then discards
2670
+ // the rest of the upload itself and the client reads the 413. With `connection: close`
2671
+ // the socket shuts while the client is still sending and it sees EPIPE/ECONNRESET instead
2672
+ // (measured: 3 of 8 runs with close, 0 of 8 with keep-alive, for a 100 MiB upload).
2673
+ const tooLarge = () =>
2674
+ sendJson(
2675
+ res,
2676
+ 413,
2677
+ { error: "payload-too-large", detail: "备份文件超过 32 MiB 上限 / the backup is larger than the 32 MiB limit" },
2678
+ { connection: "keep-alive" },
2679
+ );
2680
+ const declaredLength = Number(req.headers["content-length"]);
2681
+ if (Number.isFinite(declaredLength) && declaredLength > MAX_RESTORE_BODY_BYTES) return tooLarge();
2682
+ let raw;
2683
+ try {
2684
+ raw = await readBody(req, MAX_RESTORE_BODY_BYTES);
2685
+ } catch (err) {
2686
+ if (err?.status === 413) return tooLarge();
2687
+ return error(res, 400, "bad-request", "请求体读取失败 / the request body could not be read");
2688
+ }
2689
+ let payload;
2690
+ try {
2691
+ payload = JSON.parse(raw);
2692
+ } catch {
2693
+ return error(res, 400, "bad-request", "请求体不是合法 JSON");
2694
+ }
2695
+ // T-63: a backup with a passphrase. The body is either `{ passphrase, backup }` or the
2696
+ // encrypted file itself with the passphrase in `x-backup-passphrase`.
2697
+ let passphrase = req.headers["x-backup-passphrase"];
2698
+ if (payload && typeof payload === "object" && payload.format === undefined && payload.backup !== undefined) {
2699
+ passphrase = payload.passphrase ?? passphrase;
2700
+ payload = payload.backup;
2701
+ }
2702
+ if (isEncryptedBackup(payload)) {
2703
+ try {
2704
+ payload = decryptBackup(payload, typeof passphrase === "string" ? passphrase : undefined);
2705
+ } catch (err) {
2706
+ return error(res, 400, err?.code ?? "bad-backup", err?.message ?? "备份解不开");
2707
+ }
2708
+ }
2709
+ const dryRun = url.searchParams.get("dryRun") === "1";
2710
+ // 恢复要写记忆与人格,两者都可能没开:分别取值,别让一个缺失把整次恢复否掉。
2711
+ let store = null;
2712
+ try {
2713
+ store = getMemoryStore();
2714
+ } catch (err) {
2715
+ // 库打不开时明确拒绝,而不是"恢复成功但什么都没写"。
2716
+ return error(res, 503, "memory-unavailable", `记忆库打不开:${err?.message ?? err}`);
2717
+ }
2718
+ if (dryRun) {
2719
+ const plan = planRestore(payload, { store, prefs: assistantPrefs });
2720
+ if (!plan.ok) {
2721
+ return error(res, 400, "bad-backup", plan.error ?? "备份不合法");
2722
+ }
2723
+ // 预览里不回传 text 原文:它是用户隐私,且这一页只需要计数与原因。
2724
+ sendJson(res, 200, {
2725
+ ok: true,
2726
+ dryRun: true,
2727
+ backupVersion: plan.backupVersion,
2728
+ createdAt: plan.createdAt,
2729
+ counts: plan.counts,
2730
+ skipped: plan.skipped.slice(0, 50),
2731
+ assistant: plan.assistant,
2732
+ });
2733
+ return;
2734
+ }
2735
+ const result = applyRestore(payload, { store, prefs: assistantPrefs });
2736
+ if (!result.ok) {
2737
+ return error(res, 400, "bad-backup", result.error ?? "备份不合法");
2738
+ }
2739
+ sendJson(res, 200, { ok: true, ...result });
2740
+ return;
2741
+ }
2742
+
2111
2743
  if (new Set(["/git/capabilities", "/git/repository", "/git/branches", "/git/graph", "/git/commit", "/git/worktree", "/git/preview"]).has(rest)) {
2112
2744
  if (requireGet(method, res)) return;
2113
2745
  const sessionId = url.searchParams.get("sessionId") ?? "";
@@ -2177,6 +2809,8 @@ export function apply(ctx, configInput) {
2177
2809
  enabled: relay !== null,
2178
2810
  ...(relay
2179
2811
  ? {
2812
+ // 待命 = 允许使用中继,但现在没有连着:没有已配对的手机,也没有有效的配对码
2813
+ standby: !relay.demand.active,
2180
2814
  roomId: relay.identity.roomId,
2181
2815
  publicKey: relayB64u.enc(relay.identity.x.pub),
2182
2816
  relays: relay.connector.status(),
@@ -2192,13 +2826,20 @@ export function apply(ctx, configInput) {
2192
2826
  const gate = localDesktopGate(req);
2193
2827
  if (!gate.ok) return error(res, 403, gate.code, gate.detail);
2194
2828
  if (!relay) return error(res, 409, "relay-disabled", "未启用中继:在 cordis.patch.yml 的 mobile-remote 配置里设置 relay.enabled 与 relay.urls");
2829
+ // T-62 fix: a code made now would carry the key that is about to be replaced.
2830
+ if (relay.rotating) return error(res, 409, "relay-rotating", "正在更换中继密钥,请稍后再试 / the relay key is being replaced; try again in a moment");
2195
2831
  const body = await readJson(req, res, 4096);
2196
2832
  if (body === undefined) return;
2197
2833
  const { otp, expiresAt } = relay.devices.createPairing(typeof body?.deviceName === "string" ? body.deviceName : undefined);
2834
+ relay.demand.sync(); // 有了配对码:现在才连中继,等手机来(码过期没人用就再断开)
2198
2835
  const uri = buildPairingUri({ relays: relay.urls, roomId: relay.identity.roomId, pcPub: relay.identity.x.pub, otp, name: relay.name });
2199
2836
  const qr = await QRCode.toDataURL(uri, { width: 512, margin: 1, errorCorrectionLevel: "M" });
2837
+ // 本机公钥指纹:手机配对时会显示同一串数字(算法见 App 的
2838
+ // lib/relay/fingerprint.dart,两边都是 sha256 前 8 字节的十六进制)。
2839
+ // 桌面面板把它印在二维码下面,用户才能真的「核对」而不是点一下继续。
2840
+ const fingerprint = pairingFingerprintOf(relay.identity.x.pub);
2200
2841
  // 二维码里没有任何长期秘密:一次性配对码 5 分钟内有效、只能用一次;电脑的公钥本来就不是秘密。
2201
- sendJson(res, 200, { ok: true, uri, qr, expiresAt }, { "cache-control": "no-store" });
2842
+ sendJson(res, 200, { ok: true, uri, qr, fingerprint, expiresAt }, { "cache-control": "no-store" });
2202
2843
  return;
2203
2844
  }
2204
2845
  if (rest === "/relay/revoke") {
@@ -2209,7 +2850,64 @@ export function apply(ctx, configInput) {
2209
2850
  const body = await readJson(req, res, 1024);
2210
2851
  if (body === undefined) return;
2211
2852
  if (typeof body?.id !== "string" || body.id === "") return error(res, 400, "bad-request", "缺少设备 id");
2212
- sendJson(res, 200, { ok: true, revoked: relay.devices.revoke(body.id) });
2853
+ if (relay.rotating) return error(res, 409, "relay-rotating", "正在更换中继密钥,请稍后再试 / the relay key is being replaced; try again in a moment");
2854
+ if (!relay.devices.list().some((d) => d.id === body.id)) return sendJson(res, 200, { ok: true, revoked: false });
2855
+ // T-62 (E11): a revoked phone may still hold the access token and the PC's relay key.
2856
+ // Rotate both, so it cannot reach this PC again by either path.
2857
+ // - The relay identity (new keys, new room). Every other phone pinned the old key, so its
2858
+ // record goes too and it pairs again.
2859
+ // - The access token, when it is auto-managed (@auto). A token from the owner's config
2860
+ // is theirs to change: say so instead.
2861
+ // T-62 fix, sequencing: no pairing during the rotation (a code shown with the old key would
2862
+ // pair against it); every phone is kicked first and the connector keeps the room open until
2863
+ // the relay confirms each close (guest-close), so phones see 4401 "revoked", not 4503
2864
+ // "PC offline". Only then is the identity replaced. Whether to reconnect stays with the
2865
+ // on-demand logic (T-11): with nothing paired it stays in standby.
2866
+ const result = { ok: true, revoked: false, relayKeyRotated: false, tokenRotated: false, repairRequired: 0 };
2867
+ relay.rotating = true;
2868
+ try {
2869
+ relay.devices.cancelPairings();
2870
+ result.revoked = relay.devices.revoke(body.id);
2871
+ for (const device of relay.devices.list()) {
2872
+ if (relay.devices.revoke(device.id)) result.repairRequired += 1;
2873
+ }
2874
+ relay.demand?.sync();
2875
+ const acknowledged = await relay.connector.settled();
2876
+ if (!acknowledged) ctx.logger.warn("mobile-remote: the relay did not confirm every disconnect in time; rotating anyway");
2877
+ relay.connector.stop(); // normally already stopped by the on-demand logic
2878
+ // Keep the old room answering "pair again" (4401) for a while (T-62 fix).
2879
+ const until = Date.now() + RETIRED_ROOM_MS;
2880
+ retireIdentity(join(mobileRemoteStateDir(), "relay"), relay.identity, until);
2881
+ openRetiredRoom({ identity: relay.identity, until });
2882
+ const next = rotateIdentity(join(mobileRemoteStateDir(), "relay"));
2883
+ relay.connector.identity = next;
2884
+ relay.identity = next;
2885
+ result.relayKeyRotated = true;
2886
+ if (relay.demand) relay.demand.sync();
2887
+ else relay.connector.start();
2888
+ } catch (err) {
2889
+ ctx.logger.warn(`mobile-remote: relay key rotation after revoke failed: ${err?.message ?? err}`);
2890
+ } finally {
2891
+ relay.rotating = false;
2892
+ }
2893
+ if (tokenInfo.auto) {
2894
+ try {
2895
+ config.authToken = rotateAuthToken().token;
2896
+ result.tokenRotated = true;
2897
+ // T-62 fix: a stream opened with the old token would keep delivering events,
2898
+ // approvals and notifications to the revoked phone. End every token stream; the
2899
+ // phones that still have the new token reconnect.
2900
+ for (const conn of [...connections]) if (conn.dshVia === "token") dropConn(conn);
2901
+ } catch (err) {
2902
+ ctx.logger.warn(`mobile-remote: access token rotation after revoke failed: ${err?.message ?? err}`);
2903
+ }
2904
+ } else if (authEnabled) {
2905
+ result.tokenRotationSkipped = "configured";
2906
+ ctx.logger.warn(
2907
+ "mobile-remote: a device was revoked; change authToken in your config, it may still be on that phone / 已撤销设备:请在配置里更换 authToken,旧口令可能还在那台手机上",
2908
+ );
2909
+ }
2910
+ sendJson(res, 200, result);
2213
2911
  return;
2214
2912
  }
2215
2913
 
@@ -2256,7 +2954,7 @@ export function apply(ctx, configInput) {
2256
2954
  const agents = ctx.get("agents");
2257
2955
  if (!agents) return error(res, 503, "agents-unavailable");
2258
2956
  const sessionId = typeof body?.sessionId === "string" && body.sessionId ? body.sessionId : undefined;
2259
- let target = sessionId ? agents.get(sessionId) : agents.roots()[0];
2957
+ let target = sessionId ? agents.get(sessionId) : firstRootAgent(agents);
2260
2958
  // v3.1.5:休眠配置折叠回退默认时置位,finalize 在所有响应上附带 configDegraded
2261
2959
  let configDegraded = false;
2262
2960
  if (!target && sessionId) {
@@ -2392,7 +3090,7 @@ export function apply(ctx, configInput) {
2392
3090
  const sessionId = url.searchParams.get("sessionId") ?? undefined;
2393
3091
  const requestId = url.searchParams.get("requestId");
2394
3092
  if (!requestId || !/^[A-Za-z0-9-]{8,64}$/.test(requestId)) return error(res, 400, "bad-request", "invalid requestId");
2395
- const rootId = ctx.get("agents")?.roots()[0]?.id;
3093
+ const rootId = firstRootAgent(ctx.get("agents"))?.id;
2396
3094
  const key = receiptKeyOf(sessionId, rootId, requestId);
2397
3095
  // v3.0.0(热修 08):读取路径全量清理——未访问的旧回执同样清除并持久化(TTL 语义一致化)
2398
3096
  if (pruneReceipts()) persistReceipts();
@@ -2682,6 +3380,54 @@ export function apply(ctx, configInput) {
2682
3380
  return;
2683
3381
  }
2684
3382
 
3383
+ // 会话按天轮换的建议 + 恢复指引(v3.4.0,P1-17)。
3384
+ //
3385
+ // **只给建议,不自动切。** 自动新建会话会在用户正要说「接着刚才那个 bug」时
3386
+ // 把上下文断掉,那比长会话糟糕得多。App 拿到 `shouldRotate` 后自己决定是否
3387
+ // 弹出提示,切换动作由用户按下。
3388
+ if (rest === "/sessions/rotation") {
3389
+ if (requireGet(method, res)) return;
3390
+ const sessionId = url.searchParams.get("sessionId") ?? "";
3391
+ if (!sessionId) return error(res, 400, "bad-request", "sessionId is required");
3392
+ const sessions = ctx.get("sessions");
3393
+ if (!sessions) return error(res, 503, "sessions-unavailable");
3394
+
3395
+ const lastMessageAt = messageTimeMap.get(sessionId) ?? 0;
3396
+ const handle = sessions.get?.(sessionId) ?? null;
3397
+ // 「正在跑」有两种来源:活动的 agent 句柄,或事件里最后一条是未完成的轮次。
3398
+ // 用 `handle.agent?.busy` 优先——它是内核自己的判断,比我们从事件猜准。
3399
+ const busy = handle?.agent?.busy === true;
3400
+
3401
+ let events = handle?.events ?? [];
3402
+ let sessionTitle = "";
3403
+ try {
3404
+ const header = handle?.header ?? sessions.get?.(sessionId)?.header ?? null;
3405
+ sessionTitle = typeof header?.title === "string" ? header.title : "";
3406
+ } catch {
3407
+ // 标题只是锦上添花,读不到就不带。
3408
+ }
3409
+
3410
+ // 活动会话拿不到事件时,退一步读持久层(休眠会话也能给出摘要)。
3411
+ if (!Array.isArray(events) || events.length === 0) {
3412
+ const query = ctx.get("sessionQuery");
3413
+ if (query?.readSession) {
3414
+ try {
3415
+ const loaded = await loadDormantSession(query, sessionId);
3416
+ if (loaded.ok) events = loaded.snapshot.events ?? [];
3417
+ } catch {
3418
+ // 读不到就当作没有片段:仍然可以回答「该不该换」。
3419
+ }
3420
+ }
3421
+ }
3422
+
3423
+ sendJson(res, 200, {
3424
+ ok: true,
3425
+ sessionId,
3426
+ ...buildRotation({ events, lastMessageAt, busy, sessionTitle }),
3427
+ });
3428
+ return;
3429
+ }
3430
+
2685
3431
  if (rest === "/sessions") {
2686
3432
  if (requireGet(method, res)) return;
2687
3433
  const sessions = ctx.get("sessions");
@@ -3210,7 +3956,7 @@ export function apply(ctx, configInput) {
3210
3956
  // review:HEAD 会悬挂 SSE 连接(Node 对 HEAD 丢弃 body 但连接保持打开)——
3211
3957
  // 必须严格 GET-only,不能走 requireGet(其放行 HEAD)
3212
3958
  if (method !== "GET") return error(res, 405, "method-not-allowed");
3213
- connect(res);
3959
+ connect(res, relayPeerOf(req) !== null ? "relay" : "token");
3214
3960
  return;
3215
3961
  }
3216
3962
 
@@ -3829,7 +4575,12 @@ export function apply(ctx, configInput) {
3829
4575
  }
3830
4576
  if (!accountUsageInFlight) {
3831
4577
  if (forceRefresh) accountUsageLastForcedAt = now;
3832
- accountUsageInFlight = queryAccountUsage(ctx).then((body) => {
4578
+ // 手机的语言/时区只影响 DeepSeek 账号请求的身份头,不影响余额口径。
4579
+ const timezoneOffsetSeconds = Number(url.searchParams.get("tz"));
4580
+ accountUsageInFlight = queryAccountUsage(ctx, {
4581
+ locale: url.searchParams.get("lang") ?? undefined,
4582
+ timezoneOffsetSeconds: Number.isFinite(timezoneOffsetSeconds) ? timezoneOffsetSeconds : undefined,
4583
+ }).then((body) => {
3833
4584
  if (body.failedCount === 0) accountUsageCache = { at: Date.now(), body };
3834
4585
  else accountUsageCache = null;
3835
4586
  return body;
@@ -3846,7 +4597,7 @@ export function apply(ctx, configInput) {
3846
4597
  return;
3847
4598
  }
3848
4599
 
3849
- // ── 余额查询(DeepSeek 官方 /user/balance,key 不经过移动端) ──
4600
+ // ── 余额查询(DSH 登录的 DeepSeek 账号优先,其次官方 /user/balance;凭据不经过移动端) ──
3850
4601
  if (rest === "/balance") {
3851
4602
  if (requireGet(method, res)) return;
3852
4603
  const now = Date.now();
@@ -3855,6 +4606,32 @@ export function apply(ctx, configInput) {
3855
4606
  sendJson(res, 200, balanceCache.body);
3856
4607
  return;
3857
4608
  }
4609
+ // 用 DeepSeek 账号登录的用户没有 API Key:先问宿主账号服务要余额。
4610
+ const account = await queryDeepSeekAccountBalance(ctx);
4611
+ if (account.status === "ready" && account.wallets.length > 0) {
4612
+ balanceCache = {
4613
+ at: now,
4614
+ body: {
4615
+ ok: true,
4616
+ balance: {
4617
+ is_available: true,
4618
+ balance_infos: account.wallets.map((wallet) => ({
4619
+ currency: wallet.currency,
4620
+ total_balance: wallet.balance,
4621
+ })),
4622
+ },
4623
+ ...(account.bonusWallets.length > 0 ? {
4624
+ bonus_infos: account.bonusWallets.map((wallet) => ({
4625
+ currency: wallet.currency,
4626
+ total_balance: wallet.balance,
4627
+ })),
4628
+ } : {}),
4629
+ topUpUrl: account.links?.topUpUrl ?? "https://platform.deepseek.com/top_up",
4630
+ },
4631
+ };
4632
+ sendJson(res, 200, balanceCache.body);
4633
+ return;
4634
+ }
3858
4635
  let key;
3859
4636
  try {
3860
4637
  const credentials = ctx.get("credentials");
@@ -3866,7 +4643,10 @@ export function apply(ctx, configInput) {
3866
4643
  // 回退到环境变量
3867
4644
  }
3868
4645
  if (!key) key = process.env.DEEPSEEK_API_KEY;
3869
- if (!key) return error(res, 400, "no-api-key", "未配置 DEEPSEEK_API_KEY(电脑端 设置 → 模型 里填写)");
4646
+ if (!key) {
4647
+ if (account.status === "failed") return error(res, 502, "balance-failed", account.failedReason ?? "账号余额查询失败");
4648
+ return error(res, 400, "no-api-key", "未登录 DeepSeek 账号,也没有配置 DEEPSEEK_API_KEY(电脑端 设置 → 模型 里填写,或登录账号)");
4649
+ }
3870
4650
  try {
3871
4651
  const response = await fetch("https://api.deepseek.com/user/balance", {
3872
4652
  headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
@@ -3979,7 +4759,7 @@ export function apply(ctx, configInput) {
3979
4759
  // ── 环境诊断(能力探测,让个性化差异可见) ──
3980
4760
  if (rest === "/diagnostics") {
3981
4761
  if (requireGet(method, res)) return;
3982
- // 服务探测(兼容性诊断):每个内核服务缺失时的降级行为见 docs/09-compatibility.md
4762
+ // 服务探测(兼容性诊断):每个内核服务缺失时的降级行为见 docs/CONSOLIDATED-DOCUMENTATION.en.md Part 09
3983
4763
  const probe = (name) => {
3984
4764
  try {
3985
4765
  return ctx.get(name) !== undefined;
@@ -4208,10 +4988,13 @@ export function apply(ctx, configInput) {
4208
4988
  const parent = typeof body.path === "string" && body.path !== "" ? normalizeServerPath(body.path) : undefined;
4209
4989
  const name = typeof body.name === "string" ? body.name.trim() : "";
4210
4990
  if (name === "" || name === "." || name === ".." || /[\\/:*?"<>|]/.test(name)) return error(res, 400, "invalid-name", "文件夹名不合法");
4991
+ // T-62 fix: create under the same resolved parent that was checked (no "r/.." games).
4992
+ const shown = parent ? join(parent, name) : name;
4993
+ const target = join(realPathOf(parent ?? "."), name);
4994
+ if (isProtectedPath(target)) return protectedPathError(res);
4211
4995
  try {
4212
- const target = parent ? join(parent, name) : name;
4213
4996
  mkdirSync(target, { recursive: false });
4214
- sendJson(res, 200, { ok: true, path: target });
4997
+ sendJson(res, 200, { ok: true, path: shown });
4215
4998
  } catch (err) {
4216
4999
  return error(res, 400, "mkdir-failed", failureDetail(err)); // 审计 S4:错误原文只进日志,回包脱敏
4217
5000
  }
@@ -4236,8 +5019,11 @@ export function apply(ctx, configInput) {
4236
5019
  }
4237
5020
  // v3.1.1(issue #5):兜底兼容旧版 App 的 `\` 拼接(WSL 上 `/\home` 归一为 `/home`)
4238
5021
  const base = normalizeServerPath(path);
5022
+ // T-62 fix: check and list the same resolved folder (a link plus ".." cannot change it in between).
5023
+ const listed = realPathOf(base);
5024
+ if (isProtectedPath(listed)) return protectedPathError(res);
4239
5025
  try {
4240
- const entries = await readdir(base, { withFileTypes: true });
5026
+ const entries = await readdir(listed, { withFileTypes: true });
4241
5027
  const dirs = entries
4242
5028
  .filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
4243
5029
  .map((entry) => entry.name)
@@ -4254,7 +5040,7 @@ export function apply(ctx, configInput) {
4254
5040
  let size = null;
4255
5041
  let mtimeMs = null;
4256
5042
  try {
4257
- const st = statSync(join(base, entry.name));
5043
+ const st = statSync(join(listed, entry.name));
4258
5044
  size = st.size;
4259
5045
  mtimeMs = st.mtimeMs;
4260
5046
  } catch {
@@ -4271,27 +5057,58 @@ export function apply(ctx, configInput) {
4271
5057
  }
4272
5058
 
4273
5059
  // ── 文件传输(v3.1.2:B站 csborbbnc 反馈「下载上传」) ──
5060
+ // T-62 (E11): the DSH home (DSH's keys, this plugin's token, relay key, memory) is never
5061
+ // read, listed or written from the phone; see lib/protected-paths.js.
4274
5062
  // 与目录选择器同信任模型(口令鉴权 + 现有限流;路径由手机显式指定),
4275
5063
  // 上传默认落到目标会话的工作目录,下载任意可读文件路径。
4276
5064
  if (rest === "/files" && (method === "GET" || method === "HEAD")) {
4277
5065
  const path = url.searchParams.get("path");
4278
5066
  if (!path || path === "") return error(res, 400, "bad-request", "missing path");
4279
5067
  const target = resolve(normalizeServerPath(path));
5068
+ if (isProtectedPath(target)) return protectedPathError(res);
5069
+ // T-62 fix: open first, then check what was opened (fstat of the descriptor), then serve
5070
+ // from that descriptor. A hard link or /dev/fd/N to a protected file is refused, and the
5071
+ // file cannot be swapped between the check and the read.
5072
+ let fd;
5073
+ try {
5074
+ fd = openSync(target, fsConstants.O_RDONLY);
5075
+ } catch (err) {
5076
+ return error(res, 404, "file-not-found", failureDetail(err));
5077
+ }
5078
+ let fdOwned = true;
5079
+ const closeFd = () => {
5080
+ if (!fdOwned) return;
5081
+ fdOwned = false;
5082
+ try {
5083
+ closeSync(fd);
5084
+ } catch {
5085
+ /* already closed */
5086
+ }
5087
+ };
4280
5088
  try {
4281
- const st = statSync(target);
4282
- if (!st.isFile()) return error(res, 400, "not-a-file", "path is not a file");
5089
+ const st = fstatSync(fd);
5090
+ if (isProtectedFile(st)) {
5091
+ closeFd();
5092
+ return protectedPathError(res);
5093
+ }
5094
+ if (!st.isFile()) {
5095
+ closeFd();
5096
+ return error(res, 400, "not-a-file", "path is not a file");
5097
+ }
4283
5098
  const name = basename(target);
4284
5099
  // ETag 由「大小 + mtime」组成:文件被改写就变,够用且不用读内容。
4285
5100
  const etag = `"${st.size.toString(16)}-${Math.floor(st.mtimeMs).toString(16)}"`;
4286
5101
  const lastModified = new Date(st.mtimeMs).toUTCString();
4287
5102
  guardRes(res);
4288
5103
  if (ifNoneMatch(req, etag)) {
5104
+ closeFd();
4289
5105
  res.writeHead(304, { etag, "cache-control": "no-store", connection: "close" });
4290
5106
  res.end();
4291
5107
  return;
4292
5108
  }
4293
5109
  const range = parseByteRange(requestHeaderText(req, "range"), st.size);
4294
5110
  if (range && range.invalid) {
5111
+ closeFd();
4295
5112
  res.writeHead(416, {
4296
5113
  "accept-ranges": "bytes",
4297
5114
  "content-range": `bytes */${st.size}`,
@@ -4320,10 +5137,12 @@ export function apply(ctx, configInput) {
4320
5137
  };
4321
5138
  res.writeHead(range ? 206 : 200, headers);
4322
5139
  if (method === "HEAD" || st.size === 0) {
5140
+ closeFd();
4323
5141
  res.end();
4324
5142
  return;
4325
5143
  }
4326
- const source = createReadStream(target, { start, end });
5144
+ fdOwned = false; // the stream owns and closes it now
5145
+ const source = createReadStream(null, { fd, start, end, autoClose: true });
4327
5146
  // 客户端取消/断开时销毁文件流,避免 fd 泄漏。
4328
5147
  res.on("close", () => {
4329
5148
  try {
@@ -4341,6 +5160,7 @@ export function apply(ctx, configInput) {
4341
5160
  });
4342
5161
  source.pipe(res);
4343
5162
  } catch (err) {
5163
+ closeFd();
4344
5164
  return error(res, 404, "file-not-found", failureDetail(err)); // v3.1.5 S7:不再回主机绝对路径(含进程 cwd)
4345
5165
  }
4346
5166
  return;
@@ -4371,10 +5191,33 @@ export function apply(ctx, configInput) {
4371
5191
  }
4372
5192
  if (typeof dir !== "string" || dir === "") return error(res, 503, "no-workspace", "无法确定目标目录(无工作区)");
4373
5193
  const target = join(resolve(normalizeServerPath(dir)), name);
5194
+ if (isProtectedPath(target)) return protectedPathError(res);
4374
5195
  try {
4375
5196
  const buf = Buffer.from(body.data, "base64");
4376
5197
  if (buf.length === 0) return error(res, 400, "bad-request", "empty payload");
4377
- writeFileSync(target, buf);
5198
+ // T-62 fix: never follow a link at the final name (a dangling link could point into the
5199
+ // DSH home), and check what was opened before writing (a hard link to a protected file).
5200
+ // Opened without O_TRUNC: nothing is overwritten until the check has passed.
5201
+ try {
5202
+ if (lstatSync(target).isSymbolicLink()) return error(res, 400, "link-not-allowed", "目标是一个链接 / the target is a link");
5203
+ } catch {
5204
+ /* does not exist yet: fine */
5205
+ }
5206
+ let fd;
5207
+ try {
5208
+ fd = openSync(target, fsConstants.O_WRONLY | fsConstants.O_CREAT | (fsConstants.O_NOFOLLOW ?? 0), 0o644);
5209
+ } catch (err) {
5210
+ if (err?.code === "ELOOP" || err?.code === "EMLINK") return error(res, 400, "link-not-allowed", "目标是一个链接 / the target is a link");
5211
+ throw err;
5212
+ }
5213
+ try {
5214
+ const st = fstatSync(fd);
5215
+ if (isProtectedFile(st) || (st.nlink > 1 && isProtectedPath(realPathOf(target)))) return protectedPathError(res);
5216
+ if (!st.isFile()) return error(res, 400, "not-a-file", "path is not a file");
5217
+ writeFdFully(fd, buf);
5218
+ } finally {
5219
+ closeSync(fd);
5220
+ }
4378
5221
  sendJson(res, 200, { ok: true, path: target, bytes: buf.length });
4379
5222
  } catch (err) {
4380
5223
  ctx.logger.warn(`mobile-remote: /files/upload 写入失败:${err?.message ?? err}`);
@@ -4546,7 +5389,7 @@ export function apply(ctx, configInput) {
4546
5389
  // issue #30 评审 WARNING 2:目录的 `mode: "unknown"` 是宿主明确判定的**不受支持
4547
5390
  // 的历史条目**(宿主 `listDescendants` 映射为 diagnostic/unsupported),不能伪装成
4548
5391
  // 普通闲置子代理——否则消费者无法区分"不受支持"与"正常闲置",等于删掉 RPC 时
4549
- // 顺带静默删掉既有诊断语义(docs/03-api 承诺 `status` 可为 diagnostic reason)。
5392
+ // 顺带静默删掉既有诊断语义(docs/CONSOLIDATED-DOCUMENTATION.en.md Part 03 承诺 `status` 可为 diagnostic reason)。
4550
5393
  kind: row.mode === "unknown" ? "diagnostic" : "child",
4551
5394
  // 状态取自活 agent;已结束/已释放的子代理回落 inactive(与既有语义一致)
4552
5395
  status: row.mode === "unknown"
@@ -4580,7 +5423,14 @@ export function apply(ctx, configInput) {
4580
5423
  const childSessionId = typeof body.childSessionId === "string" ? body.childSessionId : "";
4581
5424
  if (!parentSessionId || !childSessionId) return error(res, 400, "parentSessionId-and-childSessionId-required");
4582
5425
  try {
4583
- await apiRpc("subagent.interrupt", { parentSessionId, childSessionId, mode: "continuable" });
5426
+ // T-02: interruptByUser (DSH 0.2.1-rc.2+); older hosts only have interruptByParent.
5427
+ // The gateway adapter sends only childSessionId; the pre-gateway HTTP path keeps the full payload.
5428
+ try {
5429
+ await apiRpc("subagent.interrupt", { parentSessionId, childSessionId, mode: "continuable" });
5430
+ } catch (err) {
5431
+ if (!isEndpointUnavailable(err)) throw err;
5432
+ await apiRpc("subagent.interruptByParent", { parentSessionId, childSessionId, mode: "continuable" });
5433
+ }
4584
5434
  sendJson(res, 200, { ok: true });
4585
5435
  } catch (err) {
4586
5436
  return error(res, ...rpcError(err, "subagent-interrupt-failed"));
@@ -4741,7 +5591,7 @@ export function apply(ctx, configInput) {
4741
5591
  const agents = ctx.get("agents");
4742
5592
  if (!agents) return error(res, 503, "agents-unavailable");
4743
5593
  const sessionId = typeof body?.sessionId === "string" && body.sessionId !== "" ? body.sessionId : undefined;
4744
- const agent = (sessionId ? agents.get(sessionId) : undefined) ?? agents.roots()[0];
5594
+ const agent = (sessionId ? agents.get(sessionId) : undefined) ?? firstRootAgent(agents);
4745
5595
  if (!agent) return error(res, 404, "no-live-agent");
4746
5596
  const synthetic = {
4747
5597
  agent,
@@ -5306,13 +6156,21 @@ export function apply(ctx, configInput) {
5306
6156
 
5307
6157
  // ── 挂载与清理 ──────────────────────────────────────────────
5308
6158
  // ── 端到端加密中继(v3.3):出站连接中继、按设备白名单放行、把手机请求回放给本机 ─────────────
5309
- // 默认开启(配置 schema 与随包补丁都指向 wss://dsh.claud.ing)。启用 = relay.enabled 且至少有一个合法的 wss:// 地址。
6159
+ // 默认允许(配置 schema 与随包补丁都指向 wss://dsh.claud.ing)。可用 = relay.enabled 且至少有一个合法的 wss:// 地址。
6160
+ // **按需连接(T-11)**:可用不等于连着——只有已经配对过手机、或刚生成了配对码时才去连中继;
6161
+ // 全新安装、从没配对过手机的电脑不产生任何中继连接(见 lib/relay/on-demand.js)。
5310
6162
  // 连接器只出站,不开入站端口;局域网地址与口令不受影响。
5311
6163
  const relayUrls = (config.relay?.urls ?? []).filter((u) => {
5312
6164
  const ok = isAllowedRelayUrl(u);
5313
6165
  if (!ok) ctx.logger.warn?.(`mobile-remote: 忽略不合法的中继地址(必须是 wss://):${u}`);
5314
6166
  return ok;
5315
6167
  });
6168
+ // 测试注入点(relayPathCheck / relayWebSocketImpl / relayTiming):生产不设。**不能直接读 `ctx.x`**:真实 cordis 的 ctx
6169
+ // 对没声明过的属性会抛错("cannot get property … without inject"),以前这三处直接读,在真实 DSH 上中继初始化一进来就抛、
6170
+ // 被下面的 catch 吞掉,中继悄悄不启用(单元测试的假 ctx 读不到只返回 undefined,所以一直没暴露)。
6171
+ const testHook = (name) => {
6172
+ try { return ctx[name]; } catch { return undefined; }
6173
+ };
5316
6174
  let relay = null;
5317
6175
  if (config.relay?.enabled && relayUrls.length === 0) {
5318
6176
  ctx.logger.warn?.("mobile-remote: relay.enabled 为 true 但没有合法的 relay.urls,中继未启用");
@@ -5332,20 +6190,52 @@ export function apply(ctx, configInput) {
5332
6190
  ipToken: bridgeIpToken,
5333
6191
  peerHeader: RELAY_PEER_HEADER,
5334
6192
  ipHeader: CLIENT_IP_HEADER,
5335
- check: ctx.relayPathCheck, // 仅测试注入;生产不设
6193
+ check: testHook("relayPathCheck"), // 仅测试注入;生产不设
5336
6194
  }),
5337
- WebSocketImpl: ctx.relayWebSocketImpl, // 仅测试注入;生产不设,用全局 WebSocket(Node ≥ 22)
5338
- timing: ctx.relayTiming, // 仅测试注入(缩短超时);生产不设
6195
+ WebSocketImpl: testHook("relayWebSocketImpl"), // 仅测试注入;生产不设,用全局 WebSocket(Node ≥ 22)
6196
+ timing: testHook("relayTiming"), // 仅测试注入(缩短超时);生产不设
5339
6197
  log: (m) => ctx.logger.warn?.(`mobile-remote: ${m}`),
5340
6198
  });
5341
- relay = { identity, devices, connector, urls: relayUrls, name: config.relay.name || hostname() };
6199
+ const demand = createRelayDemand({ connector, devices, log: (m) => ctx.logger.warn?.(`mobile-remote: ${m}`) });
6200
+ relay = { identity, devices, connector, demand, urls: relayUrls, name: config.relay.name || hostname() };
5342
6201
  } catch (err) {
5343
6202
  ctx.logger.warn?.(`mobile-remote: 中继初始化失败,已关闭:${err?.message ?? err}`);
5344
6203
  }
5345
6204
  }
6205
+ // T-62 fix: after a rotation the old room keeps answering for RETIRED_ROOM_MS. A host connection
6206
+ // with the old key and an empty device list refuses every phone with 4401, so the revoked phone
6207
+ // and the ones that must pair again hear "pair again" instead of waiting for a computer that
6208
+ // never comes. Idle it is one quiet socket (the relay answers pings itself); it closes at the
6209
+ // end of the window, and on the next start an expired entry is not reopened.
6210
+ const retiredRooms = new Set();
6211
+ const openRetiredRoom = ({ identity, until }) => {
6212
+ if (!relay || until <= Date.now()) return;
6213
+ const room = new RelayConnector({
6214
+ identity,
6215
+ devices: { authorize: () => null, onRevoke: () => () => {}, list: () => [] },
6216
+ urls: relayUrls,
6217
+ serve: () => {},
6218
+ WebSocketImpl: testHook("relayWebSocketImpl"), // see testHook: never read ctx.x directly
6219
+ timing: testHook("relayTiming"),
6220
+ log: (m) => ctx.logger.warn?.(`mobile-remote: (old room) ${m}`),
6221
+ });
6222
+ const close = () => {
6223
+ clearTimeout(timer);
6224
+ room.stop();
6225
+ retiredRooms.delete(close);
6226
+ };
6227
+ const timer = setTimeout(close, Math.min(until - Date.now(), 2 ** 31 - 1));
6228
+ timer.unref?.();
6229
+ retiredRooms.add(close);
6230
+ room.start();
6231
+ };
5346
6232
  ctx.effect(() => {
5347
- relay?.connector.start();
5348
- return () => relay?.connector.stop();
6233
+ relay?.demand.start(); // 有已配对的手机才会真的去连;否则保持待命
6234
+ if (relay) for (const retired of loadRetiredIdentities(join(mobileRemoteStateDir(), "relay"))) openRetiredRoom(retired);
6235
+ return () => {
6236
+ relay?.demand.stop();
6237
+ for (const close of [...retiredRooms]) close();
6238
+ };
5349
6239
  });
5350
6240
 
5351
6241
  ctx.effect(() => {
@@ -5369,7 +6259,7 @@ export function apply(ctx, configInput) {
5369
6259
  // 对非回环 host 直接 throw,用户 patch 也覆盖不了),手机无法直连 → 插件在 DSH 进程内
5370
6260
  // 自建 HTTP 监听,把 `${basePath}` 前缀请求**流式**转发到回环 webserver(SSE 长连可透传)。
5371
6261
  // 安全边界:①只转发移动端面;②`/api` 网关(桌面 GUI 内部 RPC)、`qr-config`、`qr.png`
5372
- // (含 token / 仅本机语义)一律不转发;③未配置 authToken 拒绝启动(LAN 暴露必须强口令);
6262
+ // (含 token / 仅本机语义)一律不转发;③口令短于 16 字符拒绝启动(LAN 暴露必须强口令;口令为空时 T-03 已改用自动生成的口令);
5373
6263
  // ④Host 头重写为回环信任值 → 下游 hostAllowed 自然放行,真实鉴权仍由 token 把关。
5374
6264
  // ── 启动时告诉人「手机 App 要填哪两项」(v3.2.4 零配置):地址 + 口令 ────────────
5375
6265
  // 只打印一次:桥监听成功 / 桥启动失败或不需要桥(web 版直接用 webserver 端口)时各自触发。
@@ -5387,6 +6277,8 @@ export function apply(ctx, configInput) {
5387
6277
  addresses,
5388
6278
  token: config.authToken,
5389
6279
  tokenIsAuto: tokenInfo.auto,
6280
+ // T-62: print the token only on the start that generated it.
6281
+ tokenNew: tokenInfo.generated === true,
5390
6282
  tokenFile: tokenInfo.file,
5391
6283
  persistError: tokenInfo.persistError,
5392
6284
  authEnabled,
@@ -5396,12 +6288,10 @@ export function apply(ctx, configInput) {
5396
6288
  }
5397
6289
  };
5398
6290
  if (lanEnabled) {
5399
- if (!authEnabled) {
5400
- ctx.logger.warn(
5401
- "mobile-remote: lanBridge 已启用但未配置 authToken —— 拒绝启动(LAN 暴露必须强口令,见 docs/04-security.md)"
5402
- );
5403
- } else if (config.authToken.length < 16) {
5404
- // v2.9.0 review(B6):LAN 暴露必须 ≥16 字符强口令(与 docs/04-security §2.1 承诺一致);
6291
+ // T-03: with the bridge on, an empty authToken is already resolved to "@auto" (effectiveAuthSetting),
6292
+ // so authEnabled is always true here. The old "bridge on but no authToken" refusal could not be reached.
6293
+ if (config.authToken.length < 16) {
6294
+ // v2.9.0 review(B6):LAN 暴露必须 ≥16 字符强口令(与 docs/CONSOLIDATED-DOCUMENTATION.en.md Part 04 §2.1 承诺一致);
5405
6295
  // 不做 schema min() 以免破坏既有用户加载——仅桥路径强制
5406
6296
  ctx.logger.warn(
5407
6297
  "mobile-remote: lanBridge 已启用但 authToken 短于 16 字符 —— 拒绝启动(LAN 暴露必须 ≥16 字符强随机口令)"
@@ -5439,7 +6329,7 @@ export function apply(ctx, configInput) {
5439
6329
  // 只转发移动端 API 面(/m/api*);任何编码/双斜杠/大小写变体到最后都会因
5440
6330
  // 上游 handleApi 的 rest 字面切片 ≠ 已知路由而 404;
5441
6331
  // **qr-config 必须显式排除**(唯一回传 authToken 的端点,LAN 不可达为硬性要求,
5442
- // 见 docs/04-security §3b);qr.png(不以 /m/api 开头天然排除)、
6332
+ // 见 docs/CONSOLIDATED-DOCUMENTATION.en.md Part 04 §3b);qr.png(不以 /m/api 开头天然排除)、
5443
6333
  // 桌面 /api RPC 网关、/m 下其它面一律 404。
5444
6334
  if (!pathname.startsWith(`${basePath}/api`) || pathname === `${basePath}/api/qr-config`) {
5445
6335
  res.writeHead(404);
@@ -5564,10 +6454,16 @@ export function apply(ctx, configInput) {
5564
6454
  if (!lanServer) announceConnection();
5565
6455
  // webServer 守卫:纯 headless 形态(无 web 服务)下插件保持无操作,不崩进程。
5566
6456
  const web = ctx.webServer && typeof ctx.webServer.register === "function" ? ctx.webServer : null;
6457
+ // T-03 (A3): DSH master makes every registered route require a DSH login (`auth` defaults to
6458
+ // "required": 503/401 without a Peer). The phone has no DSH login; it proves itself with our
6459
+ // token, so the routes opt out with "anonymous", but only while our own auth is on. With our
6460
+ // auth off (loopback-only), DSH's login stays in front. rc.5 ignores the extra field.
6461
+ const routeAuth = authEnabled ? { auth: "anonymous" } : {};
5567
6462
  const disposers = web ? [
5568
6463
  web.register({
5569
6464
  kind: "prefix",
5570
6465
  path: `${basePath}/api`,
6466
+ ...routeAuth,
5571
6467
  handler: (req, res) => {
5572
6468
  let url;
5573
6469
  try {
@@ -5592,6 +6488,7 @@ export function apply(ctx, configInput) {
5592
6488
  web.register({
5593
6489
  kind: "exact",
5594
6490
  path: `${basePath}/qr.png`,
6491
+ ...routeAuth,
5595
6492
  handler: (req, res) => {
5596
6493
  let url;
5597
6494
  try {
@@ -5614,6 +6511,8 @@ export function apply(ctx, configInput) {
5614
6511
  if (!sid) return;
5615
6512
  cancelDone(sid);
5616
6513
  activityMap.delete(sid);
6514
+ // 会话没了,这轮没落地的用户发言也不该留在内存里。
6515
+ pendingUserText.delete(sid);
5617
6516
  contextWindowMap.delete(sid);
5618
6517
  titleCache.delete(sid);
5619
6518
  lastNeedsAnswerAt.delete(sid);
@@ -5760,6 +6659,20 @@ export function apply(ctx, configInput) {
5760
6659
  clearInterval(pruneTimer);
5761
6660
  clearInterval(heldSweepTimer);
5762
6661
  persistHeld(); // 卸载前冲刷持存排队消息
6662
+ // 主动调度器:停掉 tick(状态已落盘,下次启动接着算)
6663
+ try {
6664
+ proactive.stop();
6665
+ } catch {
6666
+ // 从未启动过,忽略
6667
+ }
6668
+ breakReminder.stop();
6669
+ // 记忆库:关闭 SQLite 句柄(WAL 才会有机会 checkpoint 回主库)。
6670
+ try {
6671
+ memoryStore?.close();
6672
+ } catch {
6673
+ // 已关闭或打不开过,忽略
6674
+ }
6675
+ memoryStore = null;
5763
6676
  // v2.7.2 review:卸载时清理全部定时器与跟踪状态(避免对已 dispose 的 ctx 触发回调)
5764
6677
  for (const t of deferredAskTimers) clearTimeout(t);
5765
6678
  deferredAskTimers.clear();