@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/index.js
CHANGED
|
@@ -5,11 +5,12 @@
|
|
|
5
5
|
* 发消息(agent.followup / steer)、看进度与收通知(session/event + agent/status
|
|
6
6
|
* 事件桥 → SSE)、会话历史、二维码。
|
|
7
7
|
*
|
|
8
|
-
* 设计依据见 docs/
|
|
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,47 @@ 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, isStillAt, realPathOf, removeCreatedEntry } 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 { acceptWebSocket, rejectUpgrade } from "./relay/ws-server.js";
|
|
45
|
+
import { pairingFingerprint as pairingFingerprintOf } from "./relay/fingerprint.js";
|
|
35
46
|
import { b64u as relayB64u } from "./relay/crypto.js";
|
|
36
47
|
|
|
37
48
|
export { Config, DEFAULT_ENUMERATION_BUDGET_MS, DEFAULT_WARM_UP_TITLE_BUDGET_MS } from "./config.js";
|
|
38
49
|
import { DEFAULT_ENUMERATION_BUDGET_MS, DEFAULT_WARM_UP_TITLE_BUDGET_MS } from "./config.js";
|
|
39
50
|
import { deriveKeyRef, queryAccountUsage, queryDeepSeekAccountBalance } from "./account-usage-query.js";
|
|
40
51
|
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";
|
|
52
|
+
import { capabilityState, firstRootAgent, hostPeerSource, jobsCallerFor, jobsNeedsSessionId, readSettingsSection, readSettingsSectionStrict, wireStreamTakesControl } from "./host-compat.js";
|
|
42
53
|
import { pushToChannel as deliverPush } from "./push.js";
|
|
54
|
+
import { createProactiveScheduler } from "./proactive.js";
|
|
55
|
+
import { CHATTING_MS, DEFAULT_IDLE_MS, isUserIdle, pickMaterial } from "./proactive-material.js";
|
|
56
|
+
import { createReminderRoutes, createReminderStore } from "./reminders.js";
|
|
57
|
+
import { createBreakReminder, isUserActivityEvent } from "./break-reminder.js";
|
|
58
|
+
import { MAX_RESTORE_BODY_BYTES, applyRestore, buildBackup, decryptBackup, encryptBackup, isEncryptedBackup, passphraseProblem, planRestore } from "./backup.js";
|
|
59
|
+
import { buildRotation } from "./session-rotation.js";
|
|
60
|
+
import { inQuietHours, kindLabelOf, notifyBody, notifyHeadline, parseHm, quietHoursSuppress, shouldSuppressForQuietHours } from "./notify-copy.js";
|
|
43
61
|
import { compareSessionsForList, latestMessageTimeOf, planMessageTimePrune } from "./session-list.js";
|
|
44
|
-
import { EVENT_TIMELINE_CAPABILITIES, detailEventFor, isDetailVisibleType, isLiveTimelineRecord, isTimelineRecord, isVisibleConversationMessage, sniffImageType, summarizeEvent } from "./timeline.js";
|
|
62
|
+
import { EVENT_TIMELINE_CAPABILITIES, blocksToText, detailEventFor, isDetailVisibleType, isLiveTimelineRecord, isTimelineRecord, isVisibleConversationMessage, sniffImageType, summarizeEvent } from "./timeline.js";
|
|
45
63
|
import { EVENT_DETAIL_MAX_BYTES, SEEDED_PREFIX_ERROR_MESSAGE, TURN_OUTLINE_TIMEOUT_MS, classifyEventDetailReadError, classifyTurnOutlineReadError, createTurnOutlineQueue, raceWithDeadline, turnOutlineCapabilityOf, turnOutlineStateOf } from "./turn-outline.js";
|
|
46
64
|
export { codexProxyUrl } from "./account-usage-query.js";
|
|
47
65
|
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";
|
|
66
|
+
export { capabilityState, createInProcessPeer, firstRootAgent, hostPeerSource, jobsCallerFor, jobsNeedsSessionId, liveRootAgents, readSettingsSection, readSettingsSectionStrict, wireStreamTakesControl } from "./host-compat.js";
|
|
49
67
|
export { ntfyPublish } from "./push.js";
|
|
50
68
|
export { CORPUS_FRESH_MS, compareSessionsForList, latestMessageTimeOf, planMessageTimePrune, sessionListSortKey } from "./session-list.js";
|
|
51
69
|
export { MESSAGE_EVENT_TYPES, blocksToText, detailEventFor, isDetailVisibleType, isLiveTimelineRecord, isMessageEventType, isTimelineRecord, isVisibleConversationMessage, summarizeEvent } from "./timeline.js";
|
|
@@ -60,27 +78,299 @@ export const inject = ["webServer"];
|
|
|
60
78
|
/** 旧宿主逐个标题兜底的读取宽度:与宿主 `persistedReadConcurrency` 默认值一致(≤4)。 */
|
|
61
79
|
const TITLE_FALLBACK_READ_WIDTH = DEFAULT_TITLE_REFRESH_CONCURRENCY;
|
|
62
80
|
|
|
81
|
+
/** 助手口吻上下文的贡献名。 */
|
|
82
|
+
const ASSISTANT_CONTEXT_NAME = "mobile-remote:assistant";
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 把「现在用什么口吻、在什么模式」告诉模型。
|
|
86
|
+
*
|
|
87
|
+
* 为什么值得单独一段:人格只改通知文案的话,用户在 App 里切了人格、回到对话里
|
|
88
|
+
* 发现助手还是那个腔调——那这个开关就是假的。反过来,事实部分必须完全一致,
|
|
89
|
+
* 所以这里只写"怎么说",不写"说什么"。
|
|
90
|
+
*
|
|
91
|
+
* T-31 (D8): the persona part is the active persona card's own text, verbatim
|
|
92
|
+
* (personaPromptText); no fixed persona phrases are added. modeBrief stays: it is the
|
|
93
|
+
* work/life memory scope, not persona.
|
|
94
|
+
*
|
|
95
|
+
* @param {object} ctx 插件上下文
|
|
96
|
+
* @param {() => {mode: string}} getPrefs 每次装配时取当前值
|
|
97
|
+
* @param {() => object|null} getCard the active persona card
|
|
98
|
+
* @returns {boolean} 是否挂上(宿主没这个服务时为 false)
|
|
99
|
+
*/
|
|
100
|
+
function installAssistantContext(ctx, getPrefs, getCard) {
|
|
101
|
+
const systemPrompt = ctx.get?.("systemPrompt");
|
|
102
|
+
if (!systemPrompt || typeof systemPrompt.context !== "function") return false;
|
|
103
|
+
systemPrompt.context({
|
|
104
|
+
name: ASSISTANT_CONTEXT_NAME,
|
|
105
|
+
// 排在记忆之后:先知道"它是谁",再决定"这些记忆为什么值得提"。
|
|
106
|
+
order: 70,
|
|
107
|
+
// T-31 fix: the card is user text; the host must not interpolate {{variables}} in it.
|
|
108
|
+
interpolate: false,
|
|
109
|
+
text: (assembly) => {
|
|
110
|
+
try {
|
|
111
|
+
const { mode } = getPrefs();
|
|
112
|
+
// A delegated subagent works for its parent; the user's persona card is not for it.
|
|
113
|
+
// (Best effort: the assembly scope is the agent when the host passes one.)
|
|
114
|
+
const subagent = assembly?.scope?.session?.header?.origin === "subagent";
|
|
115
|
+
const card = subagent ? "" : personaPromptText(getCard());
|
|
116
|
+
return card === "" ? modeBrief(mode) : `${card}\n${modeBrief(mode)}`;
|
|
117
|
+
} catch {
|
|
118
|
+
return "";
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
return true;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* A-11: is this request path one of the desktop-only API endpoints (no phone token; DSH's own
|
|
127
|
+
* login on hosts with route auth)? Same rule as handleApi's `desktopOnlyRest`, plus anything that
|
|
128
|
+
* merely looks like one after case folding or percent-decoding, so a spelling can't slip past.
|
|
129
|
+
*/
|
|
130
|
+
export function isDesktopOnlyApiPath(pathname, apiPrefix) {
|
|
131
|
+
const rest = String(pathname).slice(String(apiPrefix).length);
|
|
132
|
+
if (rest === "/qr-config" || rest.startsWith("/relay/")) return true;
|
|
133
|
+
let decoded = rest;
|
|
134
|
+
try {
|
|
135
|
+
decoded = decodeURIComponent(rest);
|
|
136
|
+
} catch {
|
|
137
|
+
/* keep the raw form */
|
|
138
|
+
}
|
|
139
|
+
const folded = decoded.toLowerCase().replace(/\/+/g, "/");
|
|
140
|
+
return folded.includes("qr-config") || folded.startsWith("/relay/") || folded === "/relay";
|
|
141
|
+
}
|
|
142
|
+
|
|
63
143
|
export function apply(ctx, configInput) {
|
|
64
144
|
// 零配置(v3.2.4):把 "@auto" 口令与 "auto" 开桥在这里**一次性**解析成真实值,
|
|
65
145
|
// 之后整个函数(认证、qr-config、LAN 桥、诊断)看到的都是确定的 authToken / lanBridge.enabled。
|
|
66
|
-
const tokenInfo = resolveAuthToken(configInput.authToken);
|
|
67
146
|
const bridgeSetting = configInput.lanBridge?.enabled;
|
|
147
|
+
const lanBridgeResolved = resolveLanBridgeEnabled(bridgeSetting, {
|
|
148
|
+
webHost: ctx.webServer?.host,
|
|
149
|
+
webPort: ctx.webServer?.port,
|
|
150
|
+
bridgePort: configInput.lanBridge?.port ?? 3080,
|
|
151
|
+
});
|
|
152
|
+
// T-03 (E6): an empty authToken switches auth off only when nothing but this computer can
|
|
153
|
+
// reach the server; otherwise it is resolved exactly like "@auto".
|
|
154
|
+
const authSetting = effectiveAuthSetting(configInput.authToken, {
|
|
155
|
+
webHost: ctx.webServer?.host,
|
|
156
|
+
lanBridgeEnabled: lanBridgeResolved,
|
|
157
|
+
trustedHosts: configInput.trustedHosts,
|
|
158
|
+
relayEnabled: Boolean(configInput.relay?.enabled),
|
|
159
|
+
});
|
|
160
|
+
const tokenInfo = resolveAuthToken(authSetting);
|
|
161
|
+
if (authSetting === AUTO_TOKEN && configInput.authToken !== AUTO_TOKEN) {
|
|
162
|
+
ctx.logger.warn(
|
|
163
|
+
"mobile-remote: authToken is empty but this server is reachable from other devices (LAN, bridge, tunnel or relay), " +
|
|
164
|
+
"so a generated token is used instead / authToken 为空但服务可被其他设备访问,已改用自动生成的口令",
|
|
165
|
+
);
|
|
166
|
+
}
|
|
68
167
|
const config = {
|
|
69
168
|
...configInput,
|
|
70
169
|
authToken: tokenInfo.token,
|
|
71
170
|
lanBridge: {
|
|
72
171
|
...configInput.lanBridge,
|
|
73
|
-
enabled:
|
|
74
|
-
webHost: ctx.webServer?.host,
|
|
75
|
-
webPort: ctx.webServer?.port,
|
|
76
|
-
bridgePort: configInput.lanBridge?.port ?? 3080,
|
|
77
|
-
}),
|
|
172
|
+
enabled: lanBridgeResolved,
|
|
78
173
|
port: resolveLanBridgePort(bridgeSetting, configInput.lanBridge?.port ?? 3080, ctx.webServer?.port),
|
|
79
174
|
},
|
|
80
175
|
};
|
|
81
176
|
const basePath = config.path;
|
|
82
177
|
// 状态目录:与口令(auto-config)、中继身份同一个根,统一遵守 DSH_HOME(默认 ~/.dsh/mobile-remote)。
|
|
83
178
|
const STATE_DIR = mobileRemoteStateDir();
|
|
179
|
+
// ── 长期记忆(v3.3.0,T7)─────────────────────────────────────────────
|
|
180
|
+
// 懒加载 + 默认关闭:配置没开时完全不碰磁盘,也不创建 memory.db。
|
|
181
|
+
// 打开后仍然只有本机文件,不经过任何服务器。
|
|
182
|
+
let memoryStore = null;
|
|
183
|
+
let memoryStoreFailed = null;
|
|
184
|
+
const getMemoryStore = () => {
|
|
185
|
+
if (!config.memory?.enabled) return null;
|
|
186
|
+
if (memoryStoreFailed) throw memoryStoreFailed;
|
|
187
|
+
if (memoryStore) return memoryStore;
|
|
188
|
+
try {
|
|
189
|
+
memoryStore = openMemoryStore({ dir: STATE_DIR });
|
|
190
|
+
} catch (err) {
|
|
191
|
+
// 记下失败原因而不是每请求重试:磁盘满/权限错时反复 open 只会更糟。
|
|
192
|
+
memoryStoreFailed = err;
|
|
193
|
+
ctx.logger.warn(`mobile-remote: 记忆库打不开(${err?.message ?? err})——记忆功能不可用,其它功能不受影响`);
|
|
194
|
+
throw memoryStoreFailed;
|
|
195
|
+
}
|
|
196
|
+
return memoryStore;
|
|
197
|
+
};
|
|
198
|
+
const handleReminders = createReminderRoutes({ store: () => reminderStore });
|
|
199
|
+
const handlePersona = createPersonaRoutes({ store: () => personaCards, prefs: () => assistantPrefs.get() });
|
|
200
|
+
const handleMemory = createMemoryRoutes({
|
|
201
|
+
store: getMemoryStore,
|
|
202
|
+
// T-63: "delete all memory" while memory is off (or the store failed to open) deletes the files.
|
|
203
|
+
wipe: () => (memoryStore ? 0 : wipeMemoryFiles(STATE_DIR)),
|
|
204
|
+
// T-63 fix: what the user said this turn waits in pendingUserText until turn/end, then gets
|
|
205
|
+
// extracted into memory. "Delete all" must drop it too, or it is written back after the wipe.
|
|
206
|
+
onDeleteAll: () => pendingUserText.clear(),
|
|
207
|
+
});
|
|
208
|
+
// ── 主动消息调度器(v3.4.0,P0-5/P0-6)──────────────────────────────
|
|
209
|
+
// 与推送的分工:推送是"任务状态变了,告诉你一声"(一定有事件);主动消息是
|
|
210
|
+
// "它自己挑时候开口"(可以没有事件)。后者必须有上限、安静时段与"别插嘴",
|
|
211
|
+
// 否则很快变成骚扰——用户第一件事就是永久关掉它,功能等于没做。
|
|
212
|
+
//
|
|
213
|
+
// 默认**关闭**(`config.proactive.enabled`):用户没答应过"你可以主动找我",
|
|
214
|
+
// 就不该在升级后突然开始收到消息。与记忆库同一个原则。
|
|
215
|
+
//
|
|
216
|
+
// `nextFireAt` 落盘、每次 tick 重算,而不是排一个长 setTimeout:进程重启、
|
|
217
|
+
// 笔记本合盖、系统时间跳变之后长定时器就永久失效,用户再也等不到这条提醒。
|
|
218
|
+
// T-32 activity state for the proactive gates (§5.7). Activity = what a person does: a message
|
|
219
|
+
// typed in any client (lastTypedAt too) or a phone write request. `returned` is set when the
|
|
220
|
+
// app reconnects after the user has been idle: the moment "task news when you return" is for.
|
|
221
|
+
let lastUserActivityAt = 0;
|
|
222
|
+
let lastTypedAt = 0;
|
|
223
|
+
// T-32 fix: `returned` is set only by the main app's foreground signal (POST /presence), never
|
|
224
|
+
// by an event-stream connect: the Android floating pet keeps its own stream and reconnects
|
|
225
|
+
// after network blips while the user is away. `newsCursor`: results up to here were reported.
|
|
226
|
+
let returned = null; // { at, since }
|
|
227
|
+
let newsCursor = 0;
|
|
228
|
+
// A-14: the main app says when it goes to the background (POST /presence {state:"background"}).
|
|
229
|
+
// iOS keeps a suspended app's socket open and the Android pet keeps its own stream, so an open
|
|
230
|
+
// stream is not "the user can see it". Apps that never send "background" keep the old rule.
|
|
231
|
+
let presenceState = "foreground";
|
|
232
|
+
/** Someone can see the app now: a stream is open and the app did not say it went to the background. */
|
|
233
|
+
const appInForeground = () => connections.size > 0 && presenceState !== "background";
|
|
234
|
+
const proactiveIdleMs = () => config.proactive?.activeWindowMs ?? DEFAULT_IDLE_MS;
|
|
235
|
+
/** Sessions whose agent is running (a reminder tied to one of them waits). */
|
|
236
|
+
const runningSessions = () => {
|
|
237
|
+
try {
|
|
238
|
+
return (ctx.get("agents")?.list?.() ?? [])
|
|
239
|
+
.filter((a) => a?.status === "running" || a?.status === "busy")
|
|
240
|
+
.map((a) => agentSessionId(a));
|
|
241
|
+
} catch {
|
|
242
|
+
return [];
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
const reminderStore = createReminderStore({ dir: STATE_DIR });
|
|
246
|
+
const proactive = createProactiveScheduler({
|
|
247
|
+
dir: STATE_DIR,
|
|
248
|
+
isQuiet: () =>
|
|
249
|
+
shouldSuppressForQuietHours({
|
|
250
|
+
kind: "reminder",
|
|
251
|
+
at: new Date(),
|
|
252
|
+
runtime: assistantPrefs.get().quietHours,
|
|
253
|
+
fallback: config.quietHours,
|
|
254
|
+
}),
|
|
255
|
+
// Gate: the user has been idle ≥ 30 min (never while chatting); see isUserIdle for the return window.
|
|
256
|
+
isUserActive: () =>
|
|
257
|
+
!isUserIdle({
|
|
258
|
+
now: new Date(),
|
|
259
|
+
lastActivityAt: lastUserActivityAt,
|
|
260
|
+
lastTypedAt,
|
|
261
|
+
returnedAt: returned?.at ?? null,
|
|
262
|
+
idleMs: proactiveIdleMs(),
|
|
263
|
+
}),
|
|
264
|
+
// Gate: no session is busy (an agent is running).
|
|
265
|
+
isBusy: () => runningSessions().length > 0,
|
|
266
|
+
// User-set reminders only wait while the user is chatting right now (T-32 fix).
|
|
267
|
+
isChatting: () => Date.now() - lastTypedAt < CHATTING_MS,
|
|
268
|
+
// Real things only (lib/proactive-material.js): due reminders, waiting approvals/questions,
|
|
269
|
+
// task news on return, a morning summary. Nothing caused by absence.
|
|
270
|
+
pick: async ({ level, now, sentKeys, dueOnly = false } = {}) => {
|
|
271
|
+
const pending = [];
|
|
272
|
+
for (const [key, frame] of pendingFrames) {
|
|
273
|
+
if (!frame || typeof frame !== "object") continue;
|
|
274
|
+
const approval = key.startsWith("a:");
|
|
275
|
+
pending.push({
|
|
276
|
+
key,
|
|
277
|
+
id: approval ? String(frame.approvalId ?? key.slice(2)) : String(frame.questionId ?? frame.rpcId ?? key.slice(2)),
|
|
278
|
+
sessionId: String(frame.sessionId ?? ""),
|
|
279
|
+
approval,
|
|
280
|
+
toolName: frame.toolName ?? null,
|
|
281
|
+
at: Number(frame.at),
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
const finished = [...notifStore.values()]
|
|
285
|
+
.filter((n) => n.kind === "completed" || n.kind === "failed")
|
|
286
|
+
.map((n) => ({ kind: n.kind, time: n.time, sessionId: n.sessionId }));
|
|
287
|
+
return pickMaterial({
|
|
288
|
+
now: now ?? new Date(),
|
|
289
|
+
level,
|
|
290
|
+
sentKeys,
|
|
291
|
+
reminders: reminderStore.list(),
|
|
292
|
+
pending,
|
|
293
|
+
finished,
|
|
294
|
+
returned,
|
|
295
|
+
quietEnd: assistantPrefs.get().quietHours?.end,
|
|
296
|
+
dueOnly,
|
|
297
|
+
busySessions: runningSessions(),
|
|
298
|
+
});
|
|
299
|
+
},
|
|
300
|
+
deliver: async (item) => {
|
|
301
|
+
// With the app connected: into the notification center (mobile/notify), which the app
|
|
302
|
+
// shows. Without: the same push channels and wording layer as every other push
|
|
303
|
+
// (quiet hours, cooldown, redaction). Throw when nothing went out, so the scheduler
|
|
304
|
+
// does not count it (see pushSend).
|
|
305
|
+
// A-14: "connected" means in the foreground; a backgrounded app gets the push. When nothing
|
|
306
|
+
// went out, throw: the item is not marked sent and goes out on a later tick (the app coming
|
|
307
|
+
// back to the foreground is one).
|
|
308
|
+
if (appInForeground()) {
|
|
309
|
+
await pushNotification(item.sessionId ?? "", "reminder", item.text, item.sessionId ? {} : { fixedTitle: item.title });
|
|
310
|
+
} else {
|
|
311
|
+
const ok = await pushSend("reminder", item.sessionId ?? "", item.title ?? "", item.text);
|
|
312
|
+
if (!ok) throw new Error(connections.size > 0 ? "app-in-background-no-push-channel" : "no-push-channel");
|
|
313
|
+
}
|
|
314
|
+
// T-32 fix: results reported once are not news again on the next return.
|
|
315
|
+
if (item.kind === "news" && Number.isFinite(item.until)) {
|
|
316
|
+
newsCursor = Math.max(newsCursor, item.until);
|
|
317
|
+
returned = null;
|
|
318
|
+
}
|
|
319
|
+
},
|
|
320
|
+
log: ({ reason, at }) => {
|
|
321
|
+
// 只记判据与时刻,不记候选内容——日志也会被导出。
|
|
322
|
+
ctx.logger.info?.(`mobile-remote: 主动消息 ${reason}(${at})`);
|
|
323
|
+
},
|
|
324
|
+
config: {
|
|
325
|
+
enabled: config.proactive?.enabled === true,
|
|
326
|
+
dailyLimit: config.proactive?.dailyLimit,
|
|
327
|
+
minGapMs: config.proactive?.minGapMs,
|
|
328
|
+
tickMs: config.proactive?.tickMs,
|
|
329
|
+
},
|
|
330
|
+
});
|
|
331
|
+
// 注意:这里**只创建不启动**。`start()` 会立刻跑一次 tick,而 tick 要用到
|
|
332
|
+
// `assistantPrefs` / `pendingFrames` / `pushSend`——它们都定义在下面。
|
|
333
|
+
// 启动放在它们全部就位之后(见 `proactive.start()` 的注释)。
|
|
334
|
+
// 模式与人格必须同时作用在两处:通知措辞(下面 pushSend 已用 config.persona)
|
|
335
|
+
// 与 agent 对话上下文(这里注册)。只写手机本地的话,电脑上的助手毫不知情。
|
|
336
|
+
const assistantPrefs = createAssistantPrefs({
|
|
337
|
+
dir: STATE_DIR,
|
|
338
|
+
// quietHours from the config is the documented fallback (runtime prefs → config → 23:30–08:30).
|
|
339
|
+
// Without it here, prefs always answered the hard default and a configured window was ignored.
|
|
340
|
+
defaults: () => ({ mode: config.mode ?? "work", persona: config.persona ?? "colleague", quietHours: config.quietHours }),
|
|
341
|
+
});
|
|
342
|
+
// A-37: a quiet-hours window in the config that can't be read ("22:00:00", "10pm", "24:00") used
|
|
343
|
+
// to mean "never quiet" without a word. Say so at start and in /diagnostics.
|
|
344
|
+
const quietHoursConfigProblem = (() => {
|
|
345
|
+
const q = config.quietHours;
|
|
346
|
+
if (q === undefined || q === null) return null;
|
|
347
|
+
if (parseHm(q.start) !== null && parseHm(q.end) !== null) return null;
|
|
348
|
+
return `quietHours in the config is not "HH:MM"–"HH:MM" (start ${JSON.stringify(q.start)}, end ${JSON.stringify(q.end)}): this PC has no quiet hours from the config (only the app's own setting applies) / 配置里的安静时段格式不对(要 HH:MM),这台电脑没有按配置静音`;
|
|
349
|
+
})();
|
|
350
|
+
if (quietHoursConfigProblem) ctx.logger.warn(`mobile-remote: ${quietHoursConfigProblem}`);
|
|
351
|
+
// 记忆 → agent 上下文(T7 的「能召回」)。只登记一次,provider 每次装配时才读库:
|
|
352
|
+
// 这样记忆在对话中途被改/删,下一轮就生效,不需要重载插件。
|
|
353
|
+
// 宿主没有 systemPrompt 服务时静默降级(记忆只能存、读不到),不影响其它功能。
|
|
354
|
+
const memoryContextInstalled = installMemoryContext(
|
|
355
|
+
ctx,
|
|
356
|
+
createMemoryContextProvider({
|
|
357
|
+
// 直接给 getMemoryStore:功能没开时它返回 null,库坏了时它抛出(原因已由
|
|
358
|
+
// getMemoryStore 记过一次日志)。两种"没有记忆"由 provider 统一降级成空串,
|
|
359
|
+
// 但不在这里吞掉——吞掉之后就分不出「没开」和「坏了」。
|
|
360
|
+
getStore: getMemoryStore,
|
|
361
|
+
getMode: () => assistantPrefs.get().mode,
|
|
362
|
+
}),
|
|
363
|
+
);
|
|
364
|
+
if (config.memory?.enabled && !memoryContextInstalled) {
|
|
365
|
+
// 库有了、接口有了,但宿主没提供 systemPrompt:agent 读不到记忆。
|
|
366
|
+
// 这时候「记忆功能开着」是句假话,明确说出来,别让人以为它在工作。
|
|
367
|
+
ctx.logger.warn(
|
|
368
|
+
"mobile-remote: 宿主没有 systemPrompt 服务,长期记忆只能存、不会进入对话上下文",
|
|
369
|
+
);
|
|
370
|
+
}
|
|
371
|
+
// 人格与模式 → 对话上下文。与记忆分开注册:它们不依赖记忆库,关掉记忆也该生效。
|
|
372
|
+
const personaCards = createPersonaCardStore({ dir: STATE_DIR });
|
|
373
|
+
installAssistantContext(ctx, () => assistantPrefs.get(), () => activePersonaCard(personaCards, assistantPrefs.get()));
|
|
84
374
|
const gitRead = createGitReadService(ctx, {
|
|
85
375
|
onChanged: (repositoryId, changeKind = "refs") => broadcast({ type: "git/changed", repositoryId, changeKind }),
|
|
86
376
|
});
|
|
@@ -125,15 +415,21 @@ export function apply(ctx, configInput) {
|
|
|
125
415
|
// 连接在第一条响应结束后仍活着,旧写法会把它从集合里漏掉,卸载时就销毁不到。
|
|
126
416
|
const lanBridgeTracked = new WeakSet();
|
|
127
417
|
if (!authEnabled) {
|
|
418
|
+
// T-03: authEnabled is false only when nothing but this computer can reach the server (loopback
|
|
419
|
+
// webserver, no LAN bridge, no relay, no trustedHosts), so this is not an exposure warning: it says
|
|
420
|
+
// why a phone cannot connect and how to change that. Other devices get 401 (see the auth gate below).
|
|
128
421
|
ctx.logger.warn(
|
|
129
|
-
"mobile-remote:
|
|
422
|
+
"mobile-remote: authToken 为空,且服务只有本机可达(没有 LAN 桥、中继和 trustedHosts):只接受本机请求,其他设备会收到 401,手机目前连不上。" +
|
|
423
|
+
"要让手机连接,请删掉空的 authToken(沿用默认的 \"@auto\" 会自动生成口令),或打开 lanBridge / relay(见 docs/USER-GUIDE.zh-CN.md「安全须知」)" +
|
|
424
|
+
" / authToken is empty and only this computer can reach the server: other devices get 401 and phones cannot connect yet." +
|
|
425
|
+
" Remove the empty authToken (the default \"@auto\" generates one) or enable lanBridge / relay to connect a phone",
|
|
130
426
|
);
|
|
131
427
|
} else if (config.authToken.length < 16) {
|
|
132
428
|
// v2.9.0 review(B6):弱口令告警(仅警告不阻断,避免既有用户升级即断)
|
|
133
429
|
ctx.logger.warn("mobile-remote: authToken 短于 16 字符,建议更换为 ≥16 字符强随机口令");
|
|
134
430
|
}
|
|
135
431
|
|
|
136
|
-
// ── 移动端动作注册表服务(插件契约 v0.1,docs/
|
|
432
|
+
// ── 移动端动作注册表服务(插件契约 v0.1,docs/CONSOLIDATED-DOCUMENTATION.en.md Part 03 §6.8) ──
|
|
137
433
|
const actionEntries = new Map();
|
|
138
434
|
const mobileActions = {
|
|
139
435
|
register(spec) {
|
|
@@ -449,7 +745,7 @@ export function apply(ctx, configInput) {
|
|
|
449
745
|
const heldOf = (sessionId) => heldQueue.get(sessionId) ?? [];
|
|
450
746
|
const persistHeld = () => {
|
|
451
747
|
try {
|
|
452
|
-
mkdirSync(STATE_DIR, { recursive: true });
|
|
748
|
+
mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 });
|
|
453
749
|
const tmp = HELD_FILE + ".tmp";
|
|
454
750
|
writeFileSync(tmp, JSON.stringify({ held: Object.fromEntries(heldQueue) }), "utf8");
|
|
455
751
|
renameSync(tmp, HELD_FILE);
|
|
@@ -495,7 +791,7 @@ export function apply(ctx, configInput) {
|
|
|
495
791
|
const receiptKeyOf = (sessionId, targetId, requestId) => `${sessionId ?? `root:${targetId}`}:${requestId}`;
|
|
496
792
|
const persistReceipts = () => {
|
|
497
793
|
try {
|
|
498
|
-
mkdirSync(STATE_DIR, { recursive: true });
|
|
794
|
+
mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 });
|
|
499
795
|
const tmp = RECEIPT_FILE + ".tmp";
|
|
500
796
|
writeFileSync(tmp, JSON.stringify({ receipts: Object.fromEntries(sendReceipts) }), "utf8");
|
|
501
797
|
renameSync(tmp, RECEIPT_FILE);
|
|
@@ -678,7 +974,7 @@ export function apply(ctx, configInput) {
|
|
|
678
974
|
};
|
|
679
975
|
const persistReadIds = () => {
|
|
680
976
|
try {
|
|
681
|
-
mkdirSync(STATE_DIR, { recursive: true });
|
|
977
|
+
mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 });
|
|
682
978
|
const tmp = READ_FILE + ".tmp";
|
|
683
979
|
writeFileSync(tmp, JSON.stringify({ readNotifs: [...readIds] }), "utf8");
|
|
684
980
|
renameSync(tmp, READ_FILE);
|
|
@@ -748,7 +1044,7 @@ export function apply(ctx, configInput) {
|
|
|
748
1044
|
};
|
|
749
1045
|
const persistMessageTimesNow = () => {
|
|
750
1046
|
try {
|
|
751
|
-
mkdirSync(STATE_DIR, { recursive: true });
|
|
1047
|
+
mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 });
|
|
752
1048
|
const tmp = MESSAGE_TIME_FILE + ".tmp";
|
|
753
1049
|
writeFileSync(tmp, JSON.stringify(Object.fromEntries(messageTimeMap)), "utf8");
|
|
754
1050
|
renameSync(tmp, MESSAGE_TIME_FILE);
|
|
@@ -788,7 +1084,7 @@ export function apply(ctx, configInput) {
|
|
|
788
1084
|
};
|
|
789
1085
|
const persistActivityNow = () => {
|
|
790
1086
|
try {
|
|
791
|
-
mkdirSync(STATE_DIR, { recursive: true });
|
|
1087
|
+
mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 });
|
|
792
1088
|
const tmp = ACTIVITY_FILE + ".tmp";
|
|
793
1089
|
writeFileSync(tmp, JSON.stringify(Object.fromEntries(activityMap)), "utf8");
|
|
794
1090
|
renameSync(tmp, ACTIVITY_FILE);
|
|
@@ -976,13 +1272,15 @@ export function apply(ctx, configInput) {
|
|
|
976
1272
|
}
|
|
977
1273
|
return undefined;
|
|
978
1274
|
};
|
|
979
|
-
|
|
1275
|
+
// `fixedTitle` (T-15): a notification that belongs to no session (sessionId "") brings its own
|
|
1276
|
+
// title; there is no session title to look up or wait for.
|
|
1277
|
+
const pushNotification = async (sessionId, kind, detail, { fixedTitle } = {}) => {
|
|
980
1278
|
const sessions = ctx.get("sessions");
|
|
981
1279
|
let session = sessions?.get(sessionId);
|
|
982
|
-
let title = notifyTitle(sessionId, session);
|
|
1280
|
+
let title = fixedTitle ?? notifyTitle(sessionId, session);
|
|
983
1281
|
// v3.1.2(悬浮球反馈):会话标题由 LLM 异步生成,常晚于「任务完成」通知几秒才落地——
|
|
984
1282
|
// 等一小段再读一次,避免通知显示会话短码而非名称。
|
|
985
|
-
if (title === shortSessionId(sessionId)) {
|
|
1283
|
+
if (fixedTitle === undefined && title === shortSessionId(sessionId)) {
|
|
986
1284
|
await new Promise((resolve) => setTimeout(resolve, 4000));
|
|
987
1285
|
session = sessions?.get(sessionId);
|
|
988
1286
|
title = notifyTitle(sessionId, session);
|
|
@@ -1012,24 +1310,66 @@ export function apply(ctx, configInput) {
|
|
|
1012
1310
|
// v2.6.0 推送脱敏:minimal(默认)只推事件类型 + 会话短码,核心内容不进第三方通道;
|
|
1013
1311
|
// standard 恢复旧行为(会话标题 + 事件详情),仅信任通道时开启。
|
|
1014
1312
|
const pushMinimal = config.pushContent !== "standard";
|
|
1313
|
+
// 返回 boolean:**是否真的交给了至少一个通道**。
|
|
1314
|
+
//
|
|
1315
|
+
// 为什么需要这个返回值:主动消息调度器要按「真的发出去了」才记账。没有通道时
|
|
1316
|
+
// 这里只能直接返回——如果让它看起来像成功,用户什么都没收到,配额却被扣了,
|
|
1317
|
+
// 那条提醒还会被永久标记为已发(`sentKeys`),等于永久丢掉一次提醒。
|
|
1015
1318
|
const pushSend = async (kind, sessionId, title, detail) => {
|
|
1016
|
-
if (config.pushUrls.length === 0) return;
|
|
1319
|
+
if (config.pushUrls.length === 0) return false;
|
|
1017
1320
|
const key = `${sessionId}:${kind}`;
|
|
1018
1321
|
const now = Date.now();
|
|
1019
1322
|
const last = pushCooldowns.get(key) ?? 0;
|
|
1020
|
-
if (now - last < config.pushCooldownMs) return; // 节流
|
|
1323
|
+
if (now - last < config.pushCooldownMs) return false; // 节流
|
|
1021
1324
|
pushCooldowns.set(key, now);
|
|
1022
|
-
|
|
1325
|
+
// 后面还有几处 `return;`(安静时段、非法时间)——它们同样意味着“没发出去”。
|
|
1326
|
+
// 统一改掉而不是让调用方去猜。
|
|
1327
|
+
const kindLabel = kindLabelOf(kind);
|
|
1023
1328
|
const shortId = shortSessionId(sessionId);
|
|
1024
|
-
|
|
1025
|
-
//
|
|
1026
|
-
//
|
|
1027
|
-
//
|
|
1028
|
-
|
|
1329
|
+
// 安静时段(T12):完成与余额这两类不吵人;「等你回答」和「失败」照发——
|
|
1330
|
+
// 它们停在那里等人,憋到早上才算真的坏了。默认窗口 23:30–08:30。
|
|
1331
|
+
//
|
|
1332
|
+
// 取值顺序是**运行时偏好 → 部署配置 → 硬默认**:App 里改的时间必须在这里
|
|
1333
|
+
// 生效,否则用户在手机上设了 22:00,夜里照样按 23:30 被吵醒(这正是 T9/T10
|
|
1334
|
+
// 修过的同一类问题:写进了手机本地、没到电脑)。
|
|
1335
|
+
if (
|
|
1336
|
+
shouldSuppressForQuietHours({
|
|
1337
|
+
kind,
|
|
1338
|
+
at: new Date(),
|
|
1339
|
+
runtime: assistantPrefs.get().quietHours,
|
|
1340
|
+
fallback: config.quietHours,
|
|
1341
|
+
})
|
|
1342
|
+
) {
|
|
1343
|
+
ctx.logger.info?.(`mobile-remote: 安静时段,跳过 ${kind} 推送(${sessionId})`);
|
|
1344
|
+
return false;
|
|
1345
|
+
}
|
|
1346
|
+
// 标题:minimal 模式只给会话短码(不把会话标题外送),
|
|
1347
|
+
// 否则用三段式润色过的角色口吻标题。detail 里可能含路径,标题不带它。
|
|
1348
|
+
const headline = notifyHeadline({
|
|
1349
|
+
kind,
|
|
1350
|
+
title: pushMinimal ? "" : title,
|
|
1351
|
+
shortId,
|
|
1352
|
+
});
|
|
1353
|
+
// 正文:三段式(做了什么 / 要你知道 / 下一步)。minimal 模式仍不带 detail——
|
|
1354
|
+
// 第三方通道是外送面,内核原文只留在服务端日志。
|
|
1355
|
+
const body = notifyBody({
|
|
1356
|
+
kind,
|
|
1357
|
+
title: "",
|
|
1358
|
+
detail: pushMinimal ? "" : redactPathText(detail),
|
|
1359
|
+
});
|
|
1360
|
+
// 兜底:极端情况下文案层返回空串,退回旧标签,绝不让通知变成空白一条。
|
|
1361
|
+
const safeHeadline = headline.trim() === "" ? kindLabel : headline;
|
|
1362
|
+
const redactedTitle = safeHeadline;
|
|
1363
|
+
const redactedDetail = body.trim() === "" ? redactPathText(detail) : body;
|
|
1364
|
+
let delivered = 0;
|
|
1029
1365
|
for (const target of config.pushUrls) {
|
|
1366
|
+
// 通道协议不变:仍传 kindLabel 作为「事件类型」,只是标题/正文换成人话。
|
|
1030
1367
|
const outcome = await pushTracked(target, kind, kindLabel, redactedTitle, redactedDetail, sessionId);
|
|
1031
1368
|
if (!outcome.ok) ctx.logger.warn(`mobile-remote: push to "${target.name}" failed: ${outcome.error}`);
|
|
1369
|
+
else delivered += 1;
|
|
1032
1370
|
}
|
|
1371
|
+
// 全部通道都失败时不谎报成功:主动消息的配额与 `sentKeys` 都按这个返回值记账。
|
|
1372
|
+
return delivered > 0;
|
|
1033
1373
|
};
|
|
1034
1374
|
// ── 真结束通知(v2.7.2)──────────────────────────────
|
|
1035
1375
|
// 多轮大任务(goal 驱动/连续队列)每轮 turn/end 只暂存结果;agent 转 idle
|
|
@@ -1188,6 +1528,17 @@ export function apply(ctx, configInput) {
|
|
|
1188
1528
|
* 默认局域网私有地址优先;只有当机器上没有任何局域网私有地址时,才把
|
|
1189
1529
|
* Tailscale CGNAT 提到最前,避免二维码首选到不可达地址。 */
|
|
1190
1530
|
const privateFirst = (ips) => orderQrAddresses(ips);
|
|
1531
|
+
/**
|
|
1532
|
+
* 局域网加密通道(T-25)的地址:LAN 桥在监听、且这台电脑有中继身份(配对与设备名单都在那里)时,
|
|
1533
|
+
* 手机可以在桥端口上直接走 Noise(`ws://<局域网地址>:<桥端口>/v1/guest/<房间号>`)。
|
|
1534
|
+
* 只报 IPv4 局域网地址,顺序与二维码一致;最多 4 个(配对链接的上限)。
|
|
1535
|
+
*/
|
|
1536
|
+
const lanNoiseUrls = () => {
|
|
1537
|
+
if (!lanBridgeListening || !relay) return [];
|
|
1538
|
+
// 桥绑在某一个地址上(不是 0.0.0.0):只有那个地址连得上
|
|
1539
|
+
const hosts = lanHost === "0.0.0.0" || lanHost === "::" ? privateFirst(ipv4Addresses()) : [lanHost];
|
|
1540
|
+
return hosts.slice(0, 4).map((ip) => `ws://${ip}:${lanPort}`);
|
|
1541
|
+
};
|
|
1191
1542
|
/** Host 校验白名单(与 dsh /api 信任围栏同思路,阻断 DNS 重绑定)。
|
|
1192
1543
|
* = 回环(含 IPv6 ::1)+ 本机全部 internal IPv4(含 Tailscale/ZeroTier/WireGuard 虚拟网段)+ 显式配置的 `trustedHosts`(内网穿透中转)。 */
|
|
1193
1544
|
/** 审计 S9:`os.networkInterfaces()` 是按请求调用里最贵的一步(每个请求一次系统枚举,
|
|
@@ -1279,6 +1630,15 @@ export function apply(ctx, configInput) {
|
|
|
1279
1630
|
const error = sendError;
|
|
1280
1631
|
// v2.7.2 review(M7):请求体解析失败统一处理——超限透传 413,其余 400
|
|
1281
1632
|
const bodyError = (err, res) => error(res, err?.status === 413 ? 413 : 400, err?.status === 413 ? "payload-too-large" : "bad-request");
|
|
1633
|
+
/** Replace a file's content through an already-checked descriptor (T-62 fix). */
|
|
1634
|
+
const writeFdFully = (fd, buf) => {
|
|
1635
|
+
ftruncateSync(fd, 0);
|
|
1636
|
+
let offset = 0;
|
|
1637
|
+
while (offset < buf.length) offset += writeSync(fd, buf, offset, buf.length - offset, offset);
|
|
1638
|
+
};
|
|
1639
|
+
/** T-62: a file route asked for the DSH home (keys, token, relay key, memory). */
|
|
1640
|
+
const protectedPathError = (res) =>
|
|
1641
|
+
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
1642
|
// Phase 1(S1):读请求体并解析 JSON;失败已响应(bodyError),返回 undefined 供调用点提前 return。
|
|
1283
1643
|
// v3.0.0:接受可选 limit 参数并透传 readBody——/send(图片 base64 大 body)传入 64MB,
|
|
1284
1644
|
// 其余端点保持默认 64KB。此前该参数被静默丢弃,图片 >64KB 即触发 req.destroy(),
|
|
@@ -1370,6 +1730,63 @@ export function apply(ctx, configInput) {
|
|
|
1370
1730
|
};
|
|
1371
1731
|
// ── 问询/审批桥(移动端弹窗):rpcId → frame 待答清单,App 重连时补发 ──
|
|
1372
1732
|
const pendingFrames = new Map(); // `q:${rpcId}` / `a:${approvalId}` -> { rpcId, at, ...frame }
|
|
1733
|
+
// 主动调度器在这里启动,而不是靠写完配置就近启动:`start()` 会**立刻**跑一次 tick,
|
|
1734
|
+
// 而 tick 要读 `pushSend`(deliver)、`assistantPrefs`(安静时段/人格)、
|
|
1735
|
+
// `pendingFrames`(候选来源)。这三者都必须已初始化——否则就是 TDZ 报错,
|
|
1736
|
+
// 插件在加载阶段直接崩掉,而不是"主动消息不工作"这么轻。
|
|
1737
|
+
if (config.proactive?.enabled) proactive.start();
|
|
1738
|
+
// ── Break reminder (T-15, §5.7, D10) ──────────────────────────────
|
|
1739
|
+
// Counts activity from clients only: user messages from any DSH client (onSessionEvent) and
|
|
1740
|
+
// write requests from the phone (handleApi). The agent's own output does not count, so an
|
|
1741
|
+
// unattended run never triggers it. Switches: `breakReminder.enabled` in the config (this PC:
|
|
1742
|
+
// false = off, true = on even without the app's switch) and `breakReminder` in the assistant
|
|
1743
|
+
// prefs (the app's setting). A-13: with neither set, it stays off, because the store apps up
|
|
1744
|
+
// to 3.2.7 have no switch and the reminder's text tells the user to use it.
|
|
1745
|
+
const breakReminder = createBreakReminder({
|
|
1746
|
+
isEnabled: () => {
|
|
1747
|
+
const pc = config.breakReminder?.enabled;
|
|
1748
|
+
if (pc === false || assistantPrefs.get().breakReminder === false) return false;
|
|
1749
|
+
return pc === true || assistantPrefs.breakReminderSetByApp();
|
|
1750
|
+
},
|
|
1751
|
+
isQuiet: (at) =>
|
|
1752
|
+
shouldSuppressForQuietHours({
|
|
1753
|
+
kind: "break",
|
|
1754
|
+
at,
|
|
1755
|
+
runtime: assistantPrefs.get().quietHours,
|
|
1756
|
+
fallback: config.quietHours,
|
|
1757
|
+
}),
|
|
1758
|
+
remind: ({ at, workedMs }) => {
|
|
1759
|
+
const phoneOnline = appInForeground(); // A-14: a backgrounded app gets the push too
|
|
1760
|
+
// Three ways out, so it is never lost:
|
|
1761
|
+
// - `break/reminder` frame: the pet stretches on it (T-29/T-40);
|
|
1762
|
+
// - a sessionless entry in the notification center (`mobile/notify`), which the app
|
|
1763
|
+
// already turns into a banner, and the Android service into a notification, even
|
|
1764
|
+
// while the socket looks connected but the app is in the background;
|
|
1765
|
+
// - a push through the configured channels when no app is connected at all.
|
|
1766
|
+
broadcast({ type: "break/reminder", at, workedMinutes: Math.floor(workedMs / 60_000) });
|
|
1767
|
+
void pushNotification("", "break", notifyBody({ kind: "break" }), { fixedTitle: notifyHeadline({ kind: "break" }) }).catch((err) => {
|
|
1768
|
+
ctx.logger.warn(`mobile-remote: break reminder notification failed: ${err?.message ?? err}`);
|
|
1769
|
+
});
|
|
1770
|
+
ctx.logger.info?.(`mobile-remote: break reminder after ${Math.floor(workedMs / 60_000)} min (phone ${phoneOnline ? "online" : "offline"})`);
|
|
1771
|
+
if (!phoneOnline) {
|
|
1772
|
+
void pushSend("break", "", "", "").catch((err) => {
|
|
1773
|
+
ctx.logger.warn(`mobile-remote: break reminder push failed: ${err?.message ?? err}`);
|
|
1774
|
+
});
|
|
1775
|
+
}
|
|
1776
|
+
},
|
|
1777
|
+
});
|
|
1778
|
+
breakReminder.start();
|
|
1779
|
+
/** A person did something (T-15, T-32). `typed`: a message typed in a DSH client. */
|
|
1780
|
+
const noteUserActivity = ({ typed = false } = {}) => {
|
|
1781
|
+
const t = Date.now();
|
|
1782
|
+
lastUserActivityAt = t;
|
|
1783
|
+
if (typed) lastTypedAt = t;
|
|
1784
|
+
breakReminder.activity();
|
|
1785
|
+
proactive.noteReaction();
|
|
1786
|
+
};
|
|
1787
|
+
// 本轮用户说的话,等 turn/end 时决定要不要记进长期记忆。
|
|
1788
|
+
// 只存最近一条:一轮里发多条时,最后一条才是这轮的结论句。
|
|
1789
|
+
const pendingUserText = new Map(); // sessionId -> text
|
|
1373
1790
|
// v2.7.2 review(M3):上限 + TTL,防"永不回答的审批/提问帧"永久残留并在每次重连全量回放
|
|
1374
1791
|
const PENDING_FRAMES_MAX = 200;
|
|
1375
1792
|
const PENDING_FRAMES_TTL = 24 * 3600 * 1000;
|
|
@@ -1383,7 +1800,8 @@ export function apply(ctx, configInput) {
|
|
|
1383
1800
|
pendingFrames.delete(oldest);
|
|
1384
1801
|
}
|
|
1385
1802
|
};
|
|
1386
|
-
|
|
1803
|
+
/** `via`: how the stream authenticated ("token" or "relay"); token streams end when the token rotates (T-62 fix). */
|
|
1804
|
+
const connect = (res, via = "token") => {
|
|
1387
1805
|
if (connections.size >= config.maxConnections) {
|
|
1388
1806
|
res.writeHead(503, { "content-type": "application/json; charset=utf-8" });
|
|
1389
1807
|
res.end(JSON.stringify({ error: "too-many-connections" }));
|
|
@@ -1391,6 +1809,7 @@ export function apply(ctx, configInput) {
|
|
|
1391
1809
|
}
|
|
1392
1810
|
// review:先挂清理监听再写头/回放——握手瞬间客户端断开时不会留下滞留连接
|
|
1393
1811
|
//(此前 close/error 监听在写完后才挂,握手即断的死连接靠 25s 心跳兜底)
|
|
1812
|
+
res.dshVia = via;
|
|
1394
1813
|
res.on("close", () => connections.delete(res));
|
|
1395
1814
|
// 半开连接:客户端进程被杀/断网后 close 可能迟迟不来,error 事件立即清理僵尸
|
|
1396
1815
|
res.on("error", () => connections.delete(res));
|
|
@@ -1400,7 +1819,7 @@ export function apply(ctx, configInput) {
|
|
|
1400
1819
|
"connection": "keep-alive",
|
|
1401
1820
|
});
|
|
1402
1821
|
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`);
|
|
1822
|
+
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
1823
|
connections.add(res);
|
|
1405
1824
|
// 补发断线期间挂起的问询/审批(与 PC 端 GUI 连接时的 pending 回放一致;超 TTL 的僵尸帧先清掉)
|
|
1406
1825
|
for (const [key, f] of pendingFrames) {
|
|
@@ -1438,6 +1857,54 @@ export function apply(ctx, configInput) {
|
|
|
1438
1857
|
// v3.1.6(issue #14 / ADR 0013):最新消息时间——只认**用户可见的对话消息**,
|
|
1439
1858
|
// 工具活动、生命周期、协议元数据、系统注入都不算。这是会话列表的新排序依据。
|
|
1440
1859
|
if (isVisibleConversationMessage(event)) touchMessageTime(session.id, event.time);
|
|
1860
|
+
// 长期记忆写入(T7 的「会记住」那一半)。
|
|
1861
|
+
// 挂在 turn/end 而不是每条 user/message 上:一轮结束才是一句完整的话,
|
|
1862
|
+
// 中途的半句常常还带着没说完的限定语(「我比较喜欢…」后面接什么,决定了
|
|
1863
|
+
// 这条该不该记)。这里只做**规则提取**,不调模型——理由见 lib/memory/extract.js。
|
|
1864
|
+
if (event.type === "user/message") {
|
|
1865
|
+
try {
|
|
1866
|
+
pendingUserText.set(session.id, blocksToText(event.data?.message?.content));
|
|
1867
|
+
} catch {
|
|
1868
|
+
// 取不到正文就算了,不影响别的功能。
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
// T-15/T-32: a message the user typed in any client is activity (break reminder, proactive
|
|
1872
|
+
// gates, silence decay); injected messages and subagent sessions are not (isUserActivityEvent).
|
|
1873
|
+
if (isUserActivityEvent(session, event)) noteUserActivity({ typed: true });
|
|
1874
|
+
if (event.type === "turn/end") {
|
|
1875
|
+
const said = pendingUserText.get(session.id);
|
|
1876
|
+
pendingUserText.delete(session.id);
|
|
1877
|
+
// 记忆默认关闭:没开时这里一次都不该碰库(getMemoryStore 会返回 null)。
|
|
1878
|
+
if (said && config.memory?.enabled) {
|
|
1879
|
+
try {
|
|
1880
|
+
const store = getMemoryStore();
|
|
1881
|
+
if (store) {
|
|
1882
|
+
const candidates = extractMemories({
|
|
1883
|
+
text: said,
|
|
1884
|
+
mode: assistantPrefs.get().mode,
|
|
1885
|
+
});
|
|
1886
|
+
if (candidates.length > 0) {
|
|
1887
|
+
const written = recordMemories({
|
|
1888
|
+
store,
|
|
1889
|
+
candidates,
|
|
1890
|
+
meta: {
|
|
1891
|
+
sessionId: session.id,
|
|
1892
|
+
// 来源写成会话标题:用户能看懂「这条是从哪次对话来的」。
|
|
1893
|
+
origin: session.header?.title ?? null,
|
|
1894
|
+
},
|
|
1895
|
+
});
|
|
1896
|
+
if (written > 0) {
|
|
1897
|
+
ctx.logger.info?.(`mobile-remote: 记住了 ${written} 条(会话 ${shortSessionId(session.id)})`);
|
|
1898
|
+
broadcast({ type: "memory/changed" });
|
|
1899
|
+
}
|
|
1900
|
+
}
|
|
1901
|
+
}
|
|
1902
|
+
} catch (err) {
|
|
1903
|
+
// 记忆写不进去绝不能影响对话本身——它是附加能力,不是主链路。
|
|
1904
|
+
ctx.logger.warn(`mobile-remote: 记忆写入失败:${err?.message ?? err}`);
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1441
1908
|
// 上下文窗口:request/context 事件携带模型上下文大小(PC 端圆环同源数据)
|
|
1442
1909
|
if (event.type === "request/context" && Number.isInteger(event.data?.contextWindow)) {
|
|
1443
1910
|
contextWindowMap.set(session.id, event.data.contextWindow);
|
|
@@ -1688,7 +2155,7 @@ export function apply(ctx, configInput) {
|
|
|
1688
2155
|
* ④ 不是浏览器跨站请求(Sec-Fetch-Site)、Origin/Referer(若有)也是回环主机;
|
|
1689
2156
|
* ⑤ 已配置 `trustedHosts`(中继形态)时默认整体关闭(`qrConfigBehindRelay`)。
|
|
1690
2157
|
* 剩余风险:②③ 能被「裸 TCP 隧道里的攻击者」自己伪造(头是他写的),所以 ⑤ 才是兜底;
|
|
1691
|
-
* 推荐拓扑是让隧道/反代指向 LAN 桥端口——桥永远不转发这些端点(见 docs/
|
|
2158
|
+
* 推荐拓扑是让隧道/反代指向 LAN 桥端口——桥永远不转发这些端点(见 docs/CONSOLIDATED-DOCUMENTATION.en.md Part 04 §3b)。
|
|
1692
2159
|
*/
|
|
1693
2160
|
const localDesktopGate = (req, { relayGuard = true } = {}) => {
|
|
1694
2161
|
const socketPeer = String(req.socket?.remoteAddress ?? "");
|
|
@@ -1726,8 +2193,8 @@ export function apply(ctx, configInput) {
|
|
|
1726
2193
|
}
|
|
1727
2194
|
return { ok: true };
|
|
1728
2195
|
};
|
|
1729
|
-
/** 首个 root agent(无 root 时退回任意 agent)。 */
|
|
1730
|
-
const firstAgent = (agents) => agents
|
|
2196
|
+
/** 首个 root agent(无 root 时退回任意 agent)。T-01: roots() is gone from DSH 0.2.2-rc.2, see firstRootAgent. */
|
|
2197
|
+
const firstAgent = (agents) => firstRootAgent(agents) ?? (typeof agents?.list === "function" ? agents.list()[0] : undefined);
|
|
1731
2198
|
/** 会话短码(统一格式:前 8 + … + 后 4;短 id 原样)。 */
|
|
1732
2199
|
const shortSessionId = (id) => (id.length > 12 ? `${id.slice(0, 8)}…${id.slice(-4)}` : id);
|
|
1733
2200
|
/** 通知标题:会话标题兜底短码。 */
|
|
@@ -2012,7 +2479,7 @@ export function apply(ctx, configInput) {
|
|
|
2012
2479
|
}
|
|
2013
2480
|
const method = req.method;
|
|
2014
2481
|
// 只给电脑桌面 GUI 的端点(qr-config、relay 管理):豁免口令(桌面没有口令),改由 localDesktopGate 把关。
|
|
2015
|
-
const desktopOnlyRest = rest === "/qr-config" || rest.startsWith("/relay/");
|
|
2482
|
+
const desktopOnlyRest = rest === "/qr-config" || rest.startsWith("/relay/"); // keep in step with isDesktopOnlyApiPath
|
|
2016
2483
|
if (desktopOnlyRest && rest !== "/qr-config" && method !== "GET" && method !== "HEAD" && crossSiteBlocked(req)) {
|
|
2017
2484
|
error(res, 403, "cross-site-blocked", "跨站请求被拒绝:请从 App 或桌面端发起");
|
|
2018
2485
|
return;
|
|
@@ -2045,13 +2512,23 @@ export function apply(ctx, configInput) {
|
|
|
2045
2512
|
return;
|
|
2046
2513
|
}
|
|
2047
2514
|
rateReset(ip);
|
|
2515
|
+
} else {
|
|
2516
|
+
// T-03 (E6): auth is off only when the server is loopback-only (effectiveAuthSetting),
|
|
2517
|
+
// so anything that is not plainly this computer means that assumption broke: another
|
|
2518
|
+
// device, a tunnel or reverse proxy (ngrok/cloudflared/Caddy arrive from 127.0.0.1 but
|
|
2519
|
+
// add forwarding headers or keep a public Host), a cross-site page. Same checks as the
|
|
2520
|
+
// desktop-only endpoints. Fail closed instead of serving it without a token.
|
|
2521
|
+
const local = localDesktopGate(req, { relayGuard: false });
|
|
2522
|
+
if (!local.ok) {
|
|
2523
|
+
error(res, 401, "auth-required", `访问口令未启用,只接受本机请求 / authentication is off, so only this computer may connect (${local.detail})`);
|
|
2524
|
+
return;
|
|
2525
|
+
}
|
|
2048
2526
|
}
|
|
2049
|
-
//
|
|
2050
|
-
//
|
|
2051
|
-
//
|
|
2052
|
-
//
|
|
2053
|
-
|
|
2054
|
-
// "未配置口令则拒绝启动/拒绝服务",那是启动策略变更(与既有部署契约冲突),另行决策。
|
|
2527
|
+
// T-15: an authenticated write from the phone is client activity for the break reminder.
|
|
2528
|
+
// Reads are left out: the app polls and reconnects in the background on its own.
|
|
2529
|
+
// A-20: /assistant counts only when it changed something (the app re-syncs it on every
|
|
2530
|
+
// reconnect); /presence decides for itself (see there).
|
|
2531
|
+
if ((method !== "GET" && method !== "HEAD") && rest !== "/presence" && rest !== "/assistant") noteUserActivity();
|
|
2055
2532
|
}
|
|
2056
2533
|
|
|
2057
2534
|
if (rest === "/bootstrap") {
|
|
@@ -2088,6 +2565,8 @@ export function apply(ctx, configInput) {
|
|
|
2088
2565
|
auth: { enabled: authEnabled },
|
|
2089
2566
|
server: { port: ctx.webServer.port, urls, path: basePath },
|
|
2090
2567
|
plugin: { name: "dsh-mobile-remote", version: pluginVersion() },
|
|
2568
|
+
// T-61: protocol range, optional features and the oldest app it works with.
|
|
2569
|
+
...protocolInfo(),
|
|
2091
2570
|
capabilities: {
|
|
2092
2571
|
eventTimeline: EVENT_TIMELINE_CAPABILITIES,
|
|
2093
2572
|
// 宿主是否**真的**挂了 `turnOutline` 投影单元、且观察接口可用,决定声明是
|
|
@@ -2095,6 +2574,9 @@ export function apply(ctx, configInput) {
|
|
|
2095
2574
|
turnOutline: turnOutlineCapabilityOf(ctx),
|
|
2096
2575
|
// v3.2.3:普通文件下载支持 Range/HEAD/ETag(大文件续传 + 前缀预览)。
|
|
2097
2576
|
fileRange: FILE_RANGE_CAPABILITIES,
|
|
2577
|
+
// T-25:局域网加密通道。有这一项 = 手机可以在这些地址上走 Noise,不再在局域网上发口令。
|
|
2578
|
+
// (T-61 的特性列表里对应 "lan-noise"。)
|
|
2579
|
+
...(lanNoiseUrls().length > 0 ? { lanNoise: { version: 1, urls: lanNoiseUrls() } } : {}),
|
|
2098
2580
|
// v3.2.4(issue #55):手机端待办等待上限(仅供显示剩余时间,结算仍以服务端为准)。
|
|
2099
2581
|
hold: {
|
|
2100
2582
|
version: 1,
|
|
@@ -2108,6 +2590,228 @@ export function apply(ctx, configInput) {
|
|
|
2108
2590
|
return;
|
|
2109
2591
|
}
|
|
2110
2592
|
|
|
2593
|
+
// Persona cards (T-31): list, import (the app gates import on its entitlement), delete.
|
|
2594
|
+
if (rest === "/persona" || rest.startsWith("/persona/")) {
|
|
2595
|
+
if (await handlePersona(req, res, rest, method)) return;
|
|
2596
|
+
}
|
|
2597
|
+
|
|
2598
|
+
// The main app came to the foreground (T-32 fix): the only signal for "the user returned".
|
|
2599
|
+
// The floating pet's event stream never sends it. `awayMs`: how long the app was in the
|
|
2600
|
+
// background (absent after a cold start). A return needs the app away ≥ the idle window and
|
|
2601
|
+
// no message typed in any client meanwhile; news is what finished since the later of the
|
|
2602
|
+
// last typed message, the app going to the background, and the last news already sent.
|
|
2603
|
+
if (rest === "/presence") {
|
|
2604
|
+
if (requirePost(method, res)) return;
|
|
2605
|
+
const body = await readJson(req, res);
|
|
2606
|
+
if (body === undefined) return;
|
|
2607
|
+
if (body?.state === "background") {
|
|
2608
|
+
// A-14: pushes go out again while the app is in the background. Not a reaction, not activity.
|
|
2609
|
+
presenceState = "background";
|
|
2610
|
+
sendJson(res, 200, { ok: true });
|
|
2611
|
+
return;
|
|
2612
|
+
}
|
|
2613
|
+
if (body?.state !== "foreground") return error(res, 400, "bad-request", "state must be \"foreground\" or \"background\"");
|
|
2614
|
+
const wasBackground = presenceState === "background";
|
|
2615
|
+
presenceState = "foreground";
|
|
2616
|
+
const t = Date.now();
|
|
2617
|
+
const idleMs = proactiveIdleMs();
|
|
2618
|
+
const awayMs = Number.isFinite(body.awayMs) && body.awayMs >= 0 ? body.awayMs : null;
|
|
2619
|
+
const wasAway = (awayMs === null || awayMs >= idleMs) && t - lastTypedAt >= idleMs;
|
|
2620
|
+
if (wasAway) {
|
|
2621
|
+
returned = { at: t, since: Math.max(lastTypedAt, awayMs === null ? 0 : t - awayMs, newsCursor) };
|
|
2622
|
+
if (config.proactive?.enabled) setImmediate(() => void proactive.tick());
|
|
2623
|
+
} else if (wasBackground && config.proactive?.enabled) {
|
|
2624
|
+
setImmediate(() => void proactive.tick()); // anything held while it was in the background
|
|
2625
|
+
}
|
|
2626
|
+
noteUserActivity(); // opening the app is a reaction (silence decay)
|
|
2627
|
+
sendJson(res, 200, { ok: true, returned: wasAway });
|
|
2628
|
+
return;
|
|
2629
|
+
}
|
|
2630
|
+
|
|
2631
|
+
// Reminders (T-32): the "coming due" material of proactive messages.
|
|
2632
|
+
if (rest === "/reminders" || rest.startsWith("/reminders/")) {
|
|
2633
|
+
if (await handleReminders(req, res, rest, method)) return;
|
|
2634
|
+
}
|
|
2635
|
+
|
|
2636
|
+
// 长期记忆(v3.3.0,T7):/api/memory 下的列表 / 检索 / 新增 / 编辑 / 删除 / 导出。
|
|
2637
|
+
if (rest === "/memory" || rest.startsWith("/memory/")) {
|
|
2638
|
+
await handleMemory(req, res, url, rest, method);
|
|
2639
|
+
return;
|
|
2640
|
+
}
|
|
2641
|
+
|
|
2642
|
+
// 助手偏好(v3.3.0,T9):读取 / 切换模式与人格。
|
|
2643
|
+
//
|
|
2644
|
+
// 为什么必须走服务端:模式决定 agent 能看到哪些记忆,人格决定它怎么说话——
|
|
2645
|
+
// 两件事都发生在电脑上。只写手机本地的话,切换只是换了一句提示,
|
|
2646
|
+
// 电脑上的助手毫不知情,用户回到对话里会发现"没变"。
|
|
2647
|
+
if (rest === "/assistant") {
|
|
2648
|
+
if (method === "GET") {
|
|
2649
|
+
sendJson(res, 200, { ok: true, ...assistantPrefs.get() });
|
|
2650
|
+
return;
|
|
2651
|
+
}
|
|
2652
|
+
if (method === "PATCH" || method === "POST") {
|
|
2653
|
+
let body;
|
|
2654
|
+
try {
|
|
2655
|
+
// readBody 返回的是原始字符串(见 http-util.js),这里必须自己 parse——
|
|
2656
|
+
// 直接当对象用会永远读到 undefined,于是非法值不被拦、正常值也写不进去。
|
|
2657
|
+
body = JSON.parse(await readBody(req));
|
|
2658
|
+
} catch {
|
|
2659
|
+
return error(res, 400, "bad-request", "请求体不是合法 JSON");
|
|
2660
|
+
}
|
|
2661
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
2662
|
+
return error(res, 400, "bad-request", "请求体必须是对象");
|
|
2663
|
+
}
|
|
2664
|
+
try {
|
|
2665
|
+
const { changed, ...next } = assistantPrefs.set({
|
|
2666
|
+
mode: body.mode,
|
|
2667
|
+
persona: body.persona,
|
|
2668
|
+
// 只有请求里带了 quietHours 才改它——App 切换模式时不该顺手
|
|
2669
|
+
// 把用户设好的安静时段冲回默认。
|
|
2670
|
+
quietHours: body.quietHours,
|
|
2671
|
+
// T-15: the app's switch for the break reminder; absent = unchanged.
|
|
2672
|
+
breakReminder: body.breakReminder,
|
|
2673
|
+
// T-31: the active persona card; absent = unchanged.
|
|
2674
|
+
personaCard: body.personaCard,
|
|
2675
|
+
});
|
|
2676
|
+
if (changed) noteUserActivity(); // A-20: an automatic re-sync is not someone working
|
|
2677
|
+
sendJson(res, 200, { ok: true, ...next });
|
|
2678
|
+
} catch (err) {
|
|
2679
|
+
// 非法值要明说,不能静默保留旧值——用户会以为切换成功了。
|
|
2680
|
+
error(res, 400, "bad-request", err?.message ?? "invalid value");
|
|
2681
|
+
}
|
|
2682
|
+
return;
|
|
2683
|
+
}
|
|
2684
|
+
sendError(res, 405, "method-not-allowed");
|
|
2685
|
+
return;
|
|
2686
|
+
}
|
|
2687
|
+
|
|
2688
|
+
// 备份 / 恢复 / 预演恢复(v3.4.0,P1-16)。
|
|
2689
|
+
//
|
|
2690
|
+
// 两条语义要分清:
|
|
2691
|
+
// POST /api/backup/restore?dryRun=1 只算计划、不写库 —— 用户先看清会写什么
|
|
2692
|
+
// POST /api/backup/restore 执行同一份计划
|
|
2693
|
+
// 预演与真恢复共用 `planRestore()`(lib/backup.js),否则预演会说"将恢复 42 条"
|
|
2694
|
+
// 而实际只写进 40 条,那就成了一句安慰话。
|
|
2695
|
+
if (rest === "/backup") {
|
|
2696
|
+
// GET:明文备份。POST {passphrase}:同一份备份,用口令加密(T-63,可选)。
|
|
2697
|
+
// 口令放在请求体里,不放 URL:URL 会进日志与历史记录。
|
|
2698
|
+
let passphrase;
|
|
2699
|
+
if (method === "POST") {
|
|
2700
|
+
const body = await readJson(req, res);
|
|
2701
|
+
if (body === undefined) return;
|
|
2702
|
+
passphrase = body?.passphrase;
|
|
2703
|
+
const problem = passphraseProblem(passphrase); // A-16: 15+ characters, not an obvious one
|
|
2704
|
+
if (problem) return error(res, 400, "weak-passphrase", problem);
|
|
2705
|
+
} else if (method !== "GET" && method !== "HEAD") {
|
|
2706
|
+
sendError(res, 405, "method-not-allowed");
|
|
2707
|
+
return;
|
|
2708
|
+
}
|
|
2709
|
+
// 「记忆没开」与「库打不开」必须分开:前者是用户的设置,后者是故障。
|
|
2710
|
+
// 都回 null 的话,备份会在故障时静默产出一份**不含记忆**的文件,
|
|
2711
|
+
// 用户存下来还以为是完整备份——比直接报错坏得多。
|
|
2712
|
+
let store = null;
|
|
2713
|
+
try {
|
|
2714
|
+
store = getMemoryStore();
|
|
2715
|
+
} catch (err) {
|
|
2716
|
+
return error(
|
|
2717
|
+
res,
|
|
2718
|
+
503,
|
|
2719
|
+
"memory-unavailable",
|
|
2720
|
+
`记忆库打不开,无法生成完整备份:${err?.message ?? err}`,
|
|
2721
|
+
);
|
|
2722
|
+
}
|
|
2723
|
+
const backup = buildBackup({
|
|
2724
|
+
// 记忆没开(null)时仍可备份人格:两块独立,不该因为一个没开就整份不给。
|
|
2725
|
+
store,
|
|
2726
|
+
prefs: assistantPrefs,
|
|
2727
|
+
});
|
|
2728
|
+
sendJson(res, 200, passphrase === undefined ? backup : await encryptBackup(backup, passphrase));
|
|
2729
|
+
return;
|
|
2730
|
+
}
|
|
2731
|
+
if (rest === "/backup/restore") {
|
|
2732
|
+
if (method !== "POST") {
|
|
2733
|
+
sendError(res, 405, "method-not-allowed");
|
|
2734
|
+
return;
|
|
2735
|
+
}
|
|
2736
|
+
// T-55 (E5): its own 32 MiB limit (the default is 64 KiB), and "too large" is told apart
|
|
2737
|
+
// from "not JSON". The 413 goes out at once, before the body is read (declared length) or
|
|
2738
|
+
// as soon as it overflows (streamed). It is sent keep-alive on purpose: Node then discards
|
|
2739
|
+
// the rest of the upload itself and the client reads the 413. With `connection: close`
|
|
2740
|
+
// the socket shuts while the client is still sending and it sees EPIPE/ECONNRESET instead
|
|
2741
|
+
// (measured: 3 of 8 runs with close, 0 of 8 with keep-alive, for a 100 MiB upload).
|
|
2742
|
+
const tooLarge = () =>
|
|
2743
|
+
sendJson(
|
|
2744
|
+
res,
|
|
2745
|
+
413,
|
|
2746
|
+
{ error: "payload-too-large", detail: "备份文件超过 32 MiB 上限 / the backup is larger than the 32 MiB limit" },
|
|
2747
|
+
{ connection: "keep-alive" },
|
|
2748
|
+
);
|
|
2749
|
+
const declaredLength = Number(req.headers["content-length"]);
|
|
2750
|
+
if (Number.isFinite(declaredLength) && declaredLength > MAX_RESTORE_BODY_BYTES) return tooLarge();
|
|
2751
|
+
let raw;
|
|
2752
|
+
try {
|
|
2753
|
+
raw = await readBody(req, MAX_RESTORE_BODY_BYTES);
|
|
2754
|
+
} catch (err) {
|
|
2755
|
+
if (err?.status === 413) return tooLarge();
|
|
2756
|
+
return error(res, 400, "bad-request", "请求体读取失败 / the request body could not be read");
|
|
2757
|
+
}
|
|
2758
|
+
let payload;
|
|
2759
|
+
try {
|
|
2760
|
+
payload = JSON.parse(raw);
|
|
2761
|
+
} catch {
|
|
2762
|
+
return error(res, 400, "bad-request", "请求体不是合法 JSON");
|
|
2763
|
+
}
|
|
2764
|
+
// T-63: a backup with a passphrase. The body is either `{ passphrase, backup }` or the
|
|
2765
|
+
// encrypted file itself with the passphrase in `x-backup-passphrase`.
|
|
2766
|
+
let passphrase = req.headers["x-backup-passphrase"];
|
|
2767
|
+
if (payload && typeof payload === "object" && payload.format === undefined && payload.backup !== undefined) {
|
|
2768
|
+
passphrase = payload.passphrase ?? passphrase;
|
|
2769
|
+
payload = payload.backup;
|
|
2770
|
+
}
|
|
2771
|
+
if (isEncryptedBackup(payload)) {
|
|
2772
|
+
try {
|
|
2773
|
+
payload = await decryptBackup(payload, typeof passphrase === "string" ? passphrase : undefined);
|
|
2774
|
+
} catch (err) {
|
|
2775
|
+
return error(res, 400, err?.code ?? "bad-backup", err?.message ?? "备份解不开");
|
|
2776
|
+
}
|
|
2777
|
+
} else if (typeof passphrase === "string" && passphrase !== "") {
|
|
2778
|
+
// A-41: a passphrase was given but the file is plain: not the file the user meant to restore.
|
|
2779
|
+
return error(res, 400, "not-encrypted", "这份备份没有设口令,和输入的口令对不上 / this backup is not protected by a passphrase; check that it is the right file");
|
|
2780
|
+
}
|
|
2781
|
+
const dryRun = url.searchParams.get("dryRun") === "1";
|
|
2782
|
+
// 恢复要写记忆与人格,两者都可能没开:分别取值,别让一个缺失把整次恢复否掉。
|
|
2783
|
+
let store = null;
|
|
2784
|
+
try {
|
|
2785
|
+
store = getMemoryStore();
|
|
2786
|
+
} catch (err) {
|
|
2787
|
+
// 库打不开时明确拒绝,而不是"恢复成功但什么都没写"。
|
|
2788
|
+
return error(res, 503, "memory-unavailable", `记忆库打不开:${err?.message ?? err}`);
|
|
2789
|
+
}
|
|
2790
|
+
if (dryRun) {
|
|
2791
|
+
const plan = planRestore(payload, { store, prefs: assistantPrefs });
|
|
2792
|
+
if (!plan.ok) {
|
|
2793
|
+
return error(res, 400, "bad-backup", plan.error ?? "备份不合法");
|
|
2794
|
+
}
|
|
2795
|
+
// 预览里不回传 text 原文:它是用户隐私,且这一页只需要计数与原因。
|
|
2796
|
+
sendJson(res, 200, {
|
|
2797
|
+
ok: true,
|
|
2798
|
+
dryRun: true,
|
|
2799
|
+
backupVersion: plan.backupVersion,
|
|
2800
|
+
createdAt: plan.createdAt,
|
|
2801
|
+
counts: plan.counts,
|
|
2802
|
+
skipped: plan.skipped.slice(0, 50),
|
|
2803
|
+
assistant: plan.assistant,
|
|
2804
|
+
});
|
|
2805
|
+
return;
|
|
2806
|
+
}
|
|
2807
|
+
const result = applyRestore(payload, { store, prefs: assistantPrefs });
|
|
2808
|
+
if (!result.ok) {
|
|
2809
|
+
return error(res, 400, "bad-backup", result.error ?? "备份不合法");
|
|
2810
|
+
}
|
|
2811
|
+
sendJson(res, 200, { ok: true, ...result });
|
|
2812
|
+
return;
|
|
2813
|
+
}
|
|
2814
|
+
|
|
2111
2815
|
if (new Set(["/git/capabilities", "/git/repository", "/git/branches", "/git/graph", "/git/commit", "/git/worktree", "/git/preview"]).has(rest)) {
|
|
2112
2816
|
if (requireGet(method, res)) return;
|
|
2113
2817
|
const sessionId = url.searchParams.get("sessionId") ?? "";
|
|
@@ -2174,9 +2878,14 @@ export function apply(ctx, configInput) {
|
|
|
2174
2878
|
if (!gate.ok) return error(res, 403, gate.code, gate.detail);
|
|
2175
2879
|
sendJson(res, 200, {
|
|
2176
2880
|
ok: true,
|
|
2177
|
-
|
|
2881
|
+
// Remote access (the relay) is allowed. The encrypted LAN path is `lanNoise` (T-71):
|
|
2882
|
+
// it can be on with the relay off.
|
|
2883
|
+
enabled: relay?.remote === true,
|
|
2884
|
+
lanNoise: lanNoiseUrls().length > 0,
|
|
2178
2885
|
...(relay
|
|
2179
2886
|
? {
|
|
2887
|
+
// 待命 = 允许使用中继,但现在没有连着:没有已配对的手机,也没有有效的配对码
|
|
2888
|
+
standby: !relay.demand.active,
|
|
2180
2889
|
roomId: relay.identity.roomId,
|
|
2181
2890
|
publicKey: relayB64u.enc(relay.identity.x.pub),
|
|
2182
2891
|
relays: relay.connector.status(),
|
|
@@ -2191,14 +2900,30 @@ export function apply(ctx, configInput) {
|
|
|
2191
2900
|
if (requirePost(method, res)) return;
|
|
2192
2901
|
const gate = localDesktopGate(req);
|
|
2193
2902
|
if (!gate.ok) return error(res, 403, gate.code, gate.detail);
|
|
2194
|
-
if (!relay) return error(res, 409, "relay-disabled", "未启用中继:在 cordis.patch.yml 的 mobile-remote 配置里设置 relay.enabled 与 relay.urls");
|
|
2195
2903
|
const body = await readJson(req, res, 4096);
|
|
2196
2904
|
if (body === undefined) return;
|
|
2197
|
-
|
|
2198
|
-
|
|
2905
|
+
// T-71 (D-01, C-15): `mode: "lan"` is the desktop's default QR, an encrypted pairing on the
|
|
2906
|
+
// local network: no relay URL, no relay connection, no account. Anything else is the
|
|
2907
|
+
// remote-access QR (relay + LAN), as before.
|
|
2908
|
+
const lanOnly = body?.mode === "lan";
|
|
2909
|
+
if (lanOnly) {
|
|
2910
|
+
if (!relay || lanNoiseUrls().length === 0) return error(res, 409, "lan-noise-unavailable", "局域网加密通道不可用(LAN 桥没有在监听)/ the encrypted LAN path is not available (the LAN bridge is not listening)");
|
|
2911
|
+
} else if (!relay?.remote) {
|
|
2912
|
+
return error(res, 409, "relay-disabled", "未启用中继:在 cordis.patch.yml 的 mobile-remote 配置里设置 relay.enabled 与 relay.urls");
|
|
2913
|
+
}
|
|
2914
|
+
// T-62 fix: a code made now would carry the key that is about to be replaced.
|
|
2915
|
+
if (relay.rotating) return error(res, 409, "relay-rotating", "正在更换中继密钥,请稍后再试 / the relay key is being replaced; try again in a moment");
|
|
2916
|
+
const { otp, expiresAt } = relay.devices.createPairing(typeof body?.deviceName === "string" ? body.deviceName : undefined, { relay: !lanOnly });
|
|
2917
|
+
relay.demand.sync(); // 有了配对码:现在才连中继,等手机来(码过期没人用就再断开)。LAN 码不算(C-04)
|
|
2918
|
+
// lan=(B8):手机在家时直接在局域网上走同一套加密,不必绕中继
|
|
2919
|
+
const uri = buildPairingUri({ relays: lanOnly ? [] : relay.urls, roomId: relay.identity.roomId, pcPub: relay.identity.x.pub, otp, name: relay.name, lan: lanNoiseUrls() });
|
|
2199
2920
|
const qr = await QRCode.toDataURL(uri, { width: 512, margin: 1, errorCorrectionLevel: "M" });
|
|
2921
|
+
// 本机公钥指纹:手机配对时会显示同一串数字(算法见 App 的
|
|
2922
|
+
// lib/relay/fingerprint.dart,两边都是 sha256 前 8 字节的十六进制)。
|
|
2923
|
+
// 桌面面板把它印在二维码下面,用户才能真的「核对」而不是点一下继续。
|
|
2924
|
+
const fingerprint = pairingFingerprintOf(relay.identity.x.pub);
|
|
2200
2925
|
// 二维码里没有任何长期秘密:一次性配对码 5 分钟内有效、只能用一次;电脑的公钥本来就不是秘密。
|
|
2201
|
-
sendJson(res, 200, { ok: true, uri, qr, expiresAt }, { "cache-control": "no-store" });
|
|
2926
|
+
sendJson(res, 200, { ok: true, uri, qr, fingerprint, expiresAt }, { "cache-control": "no-store" });
|
|
2202
2927
|
return;
|
|
2203
2928
|
}
|
|
2204
2929
|
if (rest === "/relay/revoke") {
|
|
@@ -2209,7 +2934,64 @@ export function apply(ctx, configInput) {
|
|
|
2209
2934
|
const body = await readJson(req, res, 1024);
|
|
2210
2935
|
if (body === undefined) return;
|
|
2211
2936
|
if (typeof body?.id !== "string" || body.id === "") return error(res, 400, "bad-request", "缺少设备 id");
|
|
2212
|
-
|
|
2937
|
+
if (relay.rotating) return error(res, 409, "relay-rotating", "正在更换中继密钥,请稍后再试 / the relay key is being replaced; try again in a moment");
|
|
2938
|
+
if (!relay.devices.list().some((d) => d.id === body.id)) return sendJson(res, 200, { ok: true, revoked: false });
|
|
2939
|
+
// T-62 (E11): a revoked phone may still hold the access token and the PC's relay key.
|
|
2940
|
+
// Rotate both, so it cannot reach this PC again by either path.
|
|
2941
|
+
// - The relay identity (new keys, new room). Every other phone pinned the old key, so its
|
|
2942
|
+
// record goes too and it pairs again.
|
|
2943
|
+
// - The access token, when it is auto-managed (@auto). A token from the owner's config
|
|
2944
|
+
// is theirs to change: say so instead.
|
|
2945
|
+
// T-62 fix, sequencing: no pairing during the rotation (a code shown with the old key would
|
|
2946
|
+
// pair against it); every phone is kicked first and the connector keeps the room open until
|
|
2947
|
+
// the relay confirms each close (guest-close), so phones see 4401 "revoked", not 4503
|
|
2948
|
+
// "PC offline". Only then is the identity replaced. Whether to reconnect stays with the
|
|
2949
|
+
// on-demand logic (T-11): with nothing paired it stays in standby.
|
|
2950
|
+
const result = { ok: true, revoked: false, relayKeyRotated: false, tokenRotated: false, repairRequired: 0 };
|
|
2951
|
+
relay.rotating = true;
|
|
2952
|
+
try {
|
|
2953
|
+
relay.devices.cancelPairings();
|
|
2954
|
+
result.revoked = relay.devices.revoke(body.id);
|
|
2955
|
+
for (const device of relay.devices.list()) {
|
|
2956
|
+
if (relay.devices.revoke(device.id)) result.repairRequired += 1;
|
|
2957
|
+
}
|
|
2958
|
+
relay.demand?.sync();
|
|
2959
|
+
const acknowledged = await relay.connector.settled();
|
|
2960
|
+
if (!acknowledged) ctx.logger.warn("mobile-remote: the relay did not confirm every disconnect in time; rotating anyway");
|
|
2961
|
+
relay.connector.stop(); // normally already stopped by the on-demand logic
|
|
2962
|
+
// Keep the old room answering "pair again" (4401) for a while (T-62 fix).
|
|
2963
|
+
const until = Date.now() + RETIRED_ROOM_MS;
|
|
2964
|
+
retireIdentity(join(mobileRemoteStateDir(), "relay"), relay.identity, until);
|
|
2965
|
+
openRetiredRoom({ identity: relay.identity, until });
|
|
2966
|
+
const next = rotateIdentity(join(mobileRemoteStateDir(), "relay"));
|
|
2967
|
+
relay.connector.identity = next;
|
|
2968
|
+
relay.identity = next;
|
|
2969
|
+
result.relayKeyRotated = true;
|
|
2970
|
+
if (relay.demand) relay.demand.sync();
|
|
2971
|
+
else relay.connector.start();
|
|
2972
|
+
} catch (err) {
|
|
2973
|
+
ctx.logger.warn(`mobile-remote: relay key rotation after revoke failed: ${err?.message ?? err}`);
|
|
2974
|
+
} finally {
|
|
2975
|
+
relay.rotating = false;
|
|
2976
|
+
}
|
|
2977
|
+
if (tokenInfo.auto) {
|
|
2978
|
+
try {
|
|
2979
|
+
config.authToken = rotateAuthToken().token;
|
|
2980
|
+
result.tokenRotated = true;
|
|
2981
|
+
// T-62 fix: a stream opened with the old token would keep delivering events,
|
|
2982
|
+
// approvals and notifications to the revoked phone. End every token stream; the
|
|
2983
|
+
// phones that still have the new token reconnect.
|
|
2984
|
+
for (const conn of [...connections]) if (conn.dshVia === "token") dropConn(conn);
|
|
2985
|
+
} catch (err) {
|
|
2986
|
+
ctx.logger.warn(`mobile-remote: access token rotation after revoke failed: ${err?.message ?? err}`);
|
|
2987
|
+
}
|
|
2988
|
+
} else if (authEnabled) {
|
|
2989
|
+
result.tokenRotationSkipped = "configured";
|
|
2990
|
+
ctx.logger.warn(
|
|
2991
|
+
"mobile-remote: a device was revoked; change authToken in your config, it may still be on that phone / 已撤销设备:请在配置里更换 authToken,旧口令可能还在那台手机上",
|
|
2992
|
+
);
|
|
2993
|
+
}
|
|
2994
|
+
sendJson(res, 200, result);
|
|
2213
2995
|
return;
|
|
2214
2996
|
}
|
|
2215
2997
|
|
|
@@ -2256,7 +3038,7 @@ export function apply(ctx, configInput) {
|
|
|
2256
3038
|
const agents = ctx.get("agents");
|
|
2257
3039
|
if (!agents) return error(res, 503, "agents-unavailable");
|
|
2258
3040
|
const sessionId = typeof body?.sessionId === "string" && body.sessionId ? body.sessionId : undefined;
|
|
2259
|
-
let target = sessionId ? agents.get(sessionId) : agents
|
|
3041
|
+
let target = sessionId ? agents.get(sessionId) : firstRootAgent(agents);
|
|
2260
3042
|
// v3.1.5:休眠配置折叠回退默认时置位,finalize 在所有响应上附带 configDegraded
|
|
2261
3043
|
let configDegraded = false;
|
|
2262
3044
|
if (!target && sessionId) {
|
|
@@ -2392,7 +3174,7 @@ export function apply(ctx, configInput) {
|
|
|
2392
3174
|
const sessionId = url.searchParams.get("sessionId") ?? undefined;
|
|
2393
3175
|
const requestId = url.searchParams.get("requestId");
|
|
2394
3176
|
if (!requestId || !/^[A-Za-z0-9-]{8,64}$/.test(requestId)) return error(res, 400, "bad-request", "invalid requestId");
|
|
2395
|
-
const rootId = ctx.get("agents")
|
|
3177
|
+
const rootId = firstRootAgent(ctx.get("agents"))?.id;
|
|
2396
3178
|
const key = receiptKeyOf(sessionId, rootId, requestId);
|
|
2397
3179
|
// v3.0.0(热修 08):读取路径全量清理——未访问的旧回执同样清除并持久化(TTL 语义一致化)
|
|
2398
3180
|
if (pruneReceipts()) persistReceipts();
|
|
@@ -2682,6 +3464,54 @@ export function apply(ctx, configInput) {
|
|
|
2682
3464
|
return;
|
|
2683
3465
|
}
|
|
2684
3466
|
|
|
3467
|
+
// 会话按天轮换的建议 + 恢复指引(v3.4.0,P1-17)。
|
|
3468
|
+
//
|
|
3469
|
+
// **只给建议,不自动切。** 自动新建会话会在用户正要说「接着刚才那个 bug」时
|
|
3470
|
+
// 把上下文断掉,那比长会话糟糕得多。App 拿到 `shouldRotate` 后自己决定是否
|
|
3471
|
+
// 弹出提示,切换动作由用户按下。
|
|
3472
|
+
if (rest === "/sessions/rotation") {
|
|
3473
|
+
if (requireGet(method, res)) return;
|
|
3474
|
+
const sessionId = url.searchParams.get("sessionId") ?? "";
|
|
3475
|
+
if (!sessionId) return error(res, 400, "bad-request", "sessionId is required");
|
|
3476
|
+
const sessions = ctx.get("sessions");
|
|
3477
|
+
if (!sessions) return error(res, 503, "sessions-unavailable");
|
|
3478
|
+
|
|
3479
|
+
const lastMessageAt = messageTimeMap.get(sessionId) ?? 0;
|
|
3480
|
+
const handle = sessions.get?.(sessionId) ?? null;
|
|
3481
|
+
// 「正在跑」有两种来源:活动的 agent 句柄,或事件里最后一条是未完成的轮次。
|
|
3482
|
+
// 用 `handle.agent?.busy` 优先——它是内核自己的判断,比我们从事件猜准。
|
|
3483
|
+
const busy = handle?.agent?.busy === true;
|
|
3484
|
+
|
|
3485
|
+
let events = handle?.events ?? [];
|
|
3486
|
+
let sessionTitle = "";
|
|
3487
|
+
try {
|
|
3488
|
+
const header = handle?.header ?? sessions.get?.(sessionId)?.header ?? null;
|
|
3489
|
+
sessionTitle = typeof header?.title === "string" ? header.title : "";
|
|
3490
|
+
} catch {
|
|
3491
|
+
// 标题只是锦上添花,读不到就不带。
|
|
3492
|
+
}
|
|
3493
|
+
|
|
3494
|
+
// 活动会话拿不到事件时,退一步读持久层(休眠会话也能给出摘要)。
|
|
3495
|
+
if (!Array.isArray(events) || events.length === 0) {
|
|
3496
|
+
const query = ctx.get("sessionQuery");
|
|
3497
|
+
if (query?.readSession) {
|
|
3498
|
+
try {
|
|
3499
|
+
const loaded = await loadDormantSession(query, sessionId);
|
|
3500
|
+
if (loaded.ok) events = loaded.snapshot.events ?? [];
|
|
3501
|
+
} catch {
|
|
3502
|
+
// 读不到就当作没有片段:仍然可以回答「该不该换」。
|
|
3503
|
+
}
|
|
3504
|
+
}
|
|
3505
|
+
}
|
|
3506
|
+
|
|
3507
|
+
sendJson(res, 200, {
|
|
3508
|
+
ok: true,
|
|
3509
|
+
sessionId,
|
|
3510
|
+
...buildRotation({ events, lastMessageAt, busy, sessionTitle }),
|
|
3511
|
+
});
|
|
3512
|
+
return;
|
|
3513
|
+
}
|
|
3514
|
+
|
|
2685
3515
|
if (rest === "/sessions") {
|
|
2686
3516
|
if (requireGet(method, res)) return;
|
|
2687
3517
|
const sessions = ctx.get("sessions");
|
|
@@ -3210,7 +4040,7 @@ export function apply(ctx, configInput) {
|
|
|
3210
4040
|
// review:HEAD 会悬挂 SSE 连接(Node 对 HEAD 丢弃 body 但连接保持打开)——
|
|
3211
4041
|
// 必须严格 GET-only,不能走 requireGet(其放行 HEAD)
|
|
3212
4042
|
if (method !== "GET") return error(res, 405, "method-not-allowed");
|
|
3213
|
-
connect(res);
|
|
4043
|
+
connect(res, relayPeerOf(req) !== null ? "relay" : "token");
|
|
3214
4044
|
return;
|
|
3215
4045
|
}
|
|
3216
4046
|
|
|
@@ -4013,7 +4843,7 @@ export function apply(ctx, configInput) {
|
|
|
4013
4843
|
// ── 环境诊断(能力探测,让个性化差异可见) ──
|
|
4014
4844
|
if (rest === "/diagnostics") {
|
|
4015
4845
|
if (requireGet(method, res)) return;
|
|
4016
|
-
// 服务探测(兼容性诊断):每个内核服务缺失时的降级行为见 docs/
|
|
4846
|
+
// 服务探测(兼容性诊断):每个内核服务缺失时的降级行为见 docs/CONSOLIDATED-DOCUMENTATION.en.md Part 09
|
|
4017
4847
|
const probe = (name) => {
|
|
4018
4848
|
try {
|
|
4019
4849
|
return ctx.get(name) !== undefined;
|
|
@@ -4211,6 +5041,7 @@ export function apply(ctx, configInput) {
|
|
|
4211
5041
|
"skill-catalog: 移动端新建会话已随预设装配注入技能目录(v3.1.0 起);若目录缺失请重启插件并查看本诊断",
|
|
4212
5042
|
// v3.1.6(issue #19):能力非全绿时才出现(常态不产生噪音)
|
|
4213
5043
|
...(capabilityNote ? [capabilityNote] : []),
|
|
5044
|
+
...(quietHoursConfigProblem ? [quietHoursConfigProblem] : []),
|
|
4214
5045
|
],
|
|
4215
5046
|
});
|
|
4216
5047
|
return;
|
|
@@ -4242,10 +5073,19 @@ export function apply(ctx, configInput) {
|
|
|
4242
5073
|
const parent = typeof body.path === "string" && body.path !== "" ? normalizeServerPath(body.path) : undefined;
|
|
4243
5074
|
const name = typeof body.name === "string" ? body.name.trim() : "";
|
|
4244
5075
|
if (name === "" || name === "." || name === ".." || /[\\/:*?"<>|]/.test(name)) return error(res, 400, "invalid-name", "文件夹名不合法");
|
|
5076
|
+
// T-62 fix: create under the same resolved parent that was checked (no "r/.." games).
|
|
5077
|
+
const shown = parent ? join(parent, name) : name;
|
|
5078
|
+
// A-05: a parent whose real path can't be worked out is refused, not guessed.
|
|
5079
|
+
let target;
|
|
5080
|
+
try {
|
|
5081
|
+
target = join(realPathOf(parent ?? "."), name);
|
|
5082
|
+
} catch {
|
|
5083
|
+
return protectedPathError(res);
|
|
5084
|
+
}
|
|
5085
|
+
if (isProtectedPath(target)) return protectedPathError(res);
|
|
4245
5086
|
try {
|
|
4246
|
-
const target = parent ? join(parent, name) : name;
|
|
4247
5087
|
mkdirSync(target, { recursive: false });
|
|
4248
|
-
sendJson(res, 200, { ok: true, path:
|
|
5088
|
+
sendJson(res, 200, { ok: true, path: shown });
|
|
4249
5089
|
} catch (err) {
|
|
4250
5090
|
return error(res, 400, "mkdir-failed", failureDetail(err)); // 审计 S4:错误原文只进日志,回包脱敏
|
|
4251
5091
|
}
|
|
@@ -4270,8 +5110,16 @@ export function apply(ctx, configInput) {
|
|
|
4270
5110
|
}
|
|
4271
5111
|
// v3.1.1(issue #5):兜底兼容旧版 App 的 `\` 拼接(WSL 上 `/\home` 归一为 `/home`)
|
|
4272
5112
|
const base = normalizeServerPath(path);
|
|
5113
|
+
// T-62 fix: check and list the same resolved folder (a link plus ".." cannot change it in between).
|
|
5114
|
+
let listed;
|
|
4273
5115
|
try {
|
|
4274
|
-
|
|
5116
|
+
listed = realPathOf(base);
|
|
5117
|
+
} catch {
|
|
5118
|
+
return protectedPathError(res); // A-05: unresolvable (over-long link chain, loop): fail closed
|
|
5119
|
+
}
|
|
5120
|
+
if (isProtectedPath(listed)) return protectedPathError(res);
|
|
5121
|
+
try {
|
|
5122
|
+
const entries = await readdir(listed, { withFileTypes: true });
|
|
4275
5123
|
const dirs = entries
|
|
4276
5124
|
.filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
|
|
4277
5125
|
.map((entry) => entry.name)
|
|
@@ -4288,7 +5136,7 @@ export function apply(ctx, configInput) {
|
|
|
4288
5136
|
let size = null;
|
|
4289
5137
|
let mtimeMs = null;
|
|
4290
5138
|
try {
|
|
4291
|
-
const st = statSync(join(
|
|
5139
|
+
const st = statSync(join(listed, entry.name));
|
|
4292
5140
|
size = st.size;
|
|
4293
5141
|
mtimeMs = st.mtimeMs;
|
|
4294
5142
|
} catch {
|
|
@@ -4305,27 +5153,65 @@ export function apply(ctx, configInput) {
|
|
|
4305
5153
|
}
|
|
4306
5154
|
|
|
4307
5155
|
// ── 文件传输(v3.1.2:B站 csborbbnc 反馈「下载上传」) ──
|
|
5156
|
+
// T-62 (E11): the DSH home (DSH's keys, this plugin's token, relay key, memory) is never
|
|
5157
|
+
// read, listed or written from the phone; see lib/protected-paths.js.
|
|
4308
5158
|
// 与目录选择器同信任模型(口令鉴权 + 现有限流;路径由手机显式指定),
|
|
4309
5159
|
// 上传默认落到目标会话的工作目录,下载任意可读文件路径。
|
|
4310
5160
|
if (rest === "/files" && (method === "GET" || method === "HEAD")) {
|
|
4311
5161
|
const path = url.searchParams.get("path");
|
|
4312
5162
|
if (!path || path === "") return error(res, 400, "bad-request", "missing path");
|
|
4313
5163
|
const target = resolve(normalizeServerPath(path));
|
|
5164
|
+
if (isProtectedPath(target)) return protectedPathError(res);
|
|
5165
|
+
// T-62 fix: open first, then check what was opened (fstat of the descriptor), then serve
|
|
5166
|
+
// from that descriptor. A hard link or /dev/fd/N to a protected file is refused, and the
|
|
5167
|
+
// file cannot be swapped between the check and the read.
|
|
5168
|
+
// A-07: O_NONBLOCK, so a FIFO with no writer can't block the host's only JS thread (it is then
|
|
5169
|
+
// refused as not-a-file below); regular files ignore the flag.
|
|
5170
|
+
let fd;
|
|
5171
|
+
try {
|
|
5172
|
+
fd = openSync(target, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0));
|
|
5173
|
+
} catch (err) {
|
|
5174
|
+
return error(res, 404, "file-not-found", failureDetail(err));
|
|
5175
|
+
}
|
|
5176
|
+
let fdOwned = true;
|
|
5177
|
+
const closeFd = () => {
|
|
5178
|
+
if (!fdOwned) return;
|
|
5179
|
+
fdOwned = false;
|
|
5180
|
+
try {
|
|
5181
|
+
closeSync(fd);
|
|
5182
|
+
} catch {
|
|
5183
|
+
/* already closed */
|
|
5184
|
+
}
|
|
5185
|
+
};
|
|
4314
5186
|
try {
|
|
4315
|
-
const st =
|
|
4316
|
-
if (
|
|
5187
|
+
const st = fstatSync(fd);
|
|
5188
|
+
if (isProtectedFile(st)) {
|
|
5189
|
+
closeFd();
|
|
5190
|
+
return protectedPathError(res);
|
|
5191
|
+
}
|
|
5192
|
+
if (!st.isFile()) {
|
|
5193
|
+
closeFd();
|
|
5194
|
+
return error(res, 400, "not-a-file", "path is not a file");
|
|
5195
|
+
}
|
|
5196
|
+
// A-08: the name must still lead to this same file, outside the DSH home (a swapped symlink fails this).
|
|
5197
|
+
if (!isStillAt(target, st)) {
|
|
5198
|
+
closeFd();
|
|
5199
|
+
return isProtectedPath(target) ? protectedPathError(res) : error(res, 409, "file-changed", "the file changed while it was being opened; try again");
|
|
5200
|
+
}
|
|
4317
5201
|
const name = basename(target);
|
|
4318
5202
|
// ETag 由「大小 + mtime」组成:文件被改写就变,够用且不用读内容。
|
|
4319
5203
|
const etag = `"${st.size.toString(16)}-${Math.floor(st.mtimeMs).toString(16)}"`;
|
|
4320
5204
|
const lastModified = new Date(st.mtimeMs).toUTCString();
|
|
4321
5205
|
guardRes(res);
|
|
4322
5206
|
if (ifNoneMatch(req, etag)) {
|
|
5207
|
+
closeFd();
|
|
4323
5208
|
res.writeHead(304, { etag, "cache-control": "no-store", connection: "close" });
|
|
4324
5209
|
res.end();
|
|
4325
5210
|
return;
|
|
4326
5211
|
}
|
|
4327
5212
|
const range = parseByteRange(requestHeaderText(req, "range"), st.size);
|
|
4328
5213
|
if (range && range.invalid) {
|
|
5214
|
+
closeFd();
|
|
4329
5215
|
res.writeHead(416, {
|
|
4330
5216
|
"accept-ranges": "bytes",
|
|
4331
5217
|
"content-range": `bytes */${st.size}`,
|
|
@@ -4354,10 +5240,12 @@ export function apply(ctx, configInput) {
|
|
|
4354
5240
|
};
|
|
4355
5241
|
res.writeHead(range ? 206 : 200, headers);
|
|
4356
5242
|
if (method === "HEAD" || st.size === 0) {
|
|
5243
|
+
closeFd();
|
|
4357
5244
|
res.end();
|
|
4358
5245
|
return;
|
|
4359
5246
|
}
|
|
4360
|
-
|
|
5247
|
+
fdOwned = false; // the stream owns and closes it now
|
|
5248
|
+
const source = createReadStream(null, { fd, start, end, autoClose: true });
|
|
4361
5249
|
// 客户端取消/断开时销毁文件流,避免 fd 泄漏。
|
|
4362
5250
|
res.on("close", () => {
|
|
4363
5251
|
try {
|
|
@@ -4375,6 +5263,7 @@ export function apply(ctx, configInput) {
|
|
|
4375
5263
|
});
|
|
4376
5264
|
source.pipe(res);
|
|
4377
5265
|
} catch (err) {
|
|
5266
|
+
closeFd();
|
|
4378
5267
|
return error(res, 404, "file-not-found", failureDetail(err)); // v3.1.5 S7:不再回主机绝对路径(含进程 cwd)
|
|
4379
5268
|
}
|
|
4380
5269
|
return;
|
|
@@ -4405,10 +5294,56 @@ export function apply(ctx, configInput) {
|
|
|
4405
5294
|
}
|
|
4406
5295
|
if (typeof dir !== "string" || dir === "") return error(res, 503, "no-workspace", "无法确定目标目录(无工作区)");
|
|
4407
5296
|
const target = join(resolve(normalizeServerPath(dir)), name);
|
|
5297
|
+
if (isProtectedPath(target)) return protectedPathError(res);
|
|
4408
5298
|
try {
|
|
4409
5299
|
const buf = Buffer.from(body.data, "base64");
|
|
4410
5300
|
if (buf.length === 0) return error(res, 400, "bad-request", "empty payload");
|
|
4411
|
-
|
|
5301
|
+
// T-62 fix: never follow a link at the final name (a dangling link could point into the
|
|
5302
|
+
// DSH home), and check what was opened before writing (a hard link to a protected file).
|
|
5303
|
+
// Opened without O_TRUNC: nothing is overwritten until the check has passed.
|
|
5304
|
+
try {
|
|
5305
|
+
const existing = lstatSync(target);
|
|
5306
|
+
if (existing.isSymbolicLink()) return error(res, 400, "link-not-allowed", "目标是一个链接 / the target is a link");
|
|
5307
|
+
if (!existing.isFile()) return error(res, 400, "not-a-file", "path is not a file"); // A-07: FIFO, socket, device
|
|
5308
|
+
} catch {
|
|
5309
|
+
/* does not exist yet: fine */
|
|
5310
|
+
}
|
|
5311
|
+
// O_NONBLOCK (A-07): a FIFO swapped in with no reader fails at once (ENXIO) instead of blocking.
|
|
5312
|
+
// O_EXCL first (A-08, A-45): when this call created the file, a refused upload removes it again.
|
|
5313
|
+
const base = fsConstants.O_WRONLY | (fsConstants.O_NOFOLLOW ?? 0) | (fsConstants.O_NONBLOCK ?? 0);
|
|
5314
|
+
let fd;
|
|
5315
|
+
let created = false;
|
|
5316
|
+
try {
|
|
5317
|
+
try {
|
|
5318
|
+
fd = openSync(target, base | fsConstants.O_CREAT | fsConstants.O_EXCL, 0o644);
|
|
5319
|
+
created = true;
|
|
5320
|
+
} catch (err) {
|
|
5321
|
+
if (err?.code !== "EEXIST") throw err;
|
|
5322
|
+
fd = openSync(target, base);
|
|
5323
|
+
}
|
|
5324
|
+
} catch (err) {
|
|
5325
|
+
if (err?.code === "ELOOP" || err?.code === "EMLINK") return error(res, 400, "link-not-allowed", "目标是一个链接 / the target is a link");
|
|
5326
|
+
if (err?.code === "ENXIO") return error(res, 400, "not-a-file", "path is not a file");
|
|
5327
|
+
throw err;
|
|
5328
|
+
}
|
|
5329
|
+
let refusal;
|
|
5330
|
+
let st;
|
|
5331
|
+
try {
|
|
5332
|
+
st = fstatSync(fd);
|
|
5333
|
+
if (isProtectedFile(st)) refusal = "protected";
|
|
5334
|
+
else if (!st.isFile()) refusal = "not-a-file";
|
|
5335
|
+
// A-08: the folder may have been a symlink swapped in and out; the name must still lead here.
|
|
5336
|
+
else if (!isStillAt(target, st)) refusal = isProtectedPath(target) ? "protected" : "changed";
|
|
5337
|
+
if (!refusal) writeFdFully(fd, buf);
|
|
5338
|
+
} finally {
|
|
5339
|
+
closeSync(fd);
|
|
5340
|
+
}
|
|
5341
|
+
if (refusal) {
|
|
5342
|
+
if (created) removeCreatedEntry(target, st);
|
|
5343
|
+
if (refusal === "not-a-file") return error(res, 400, "not-a-file", "path is not a file");
|
|
5344
|
+
if (refusal === "changed") return error(res, 409, "file-changed", "the folder changed while the file was being written; try again");
|
|
5345
|
+
return protectedPathError(res);
|
|
5346
|
+
}
|
|
4412
5347
|
sendJson(res, 200, { ok: true, path: target, bytes: buf.length });
|
|
4413
5348
|
} catch (err) {
|
|
4414
5349
|
ctx.logger.warn(`mobile-remote: /files/upload 写入失败:${err?.message ?? err}`);
|
|
@@ -4580,7 +5515,7 @@ export function apply(ctx, configInput) {
|
|
|
4580
5515
|
// issue #30 评审 WARNING 2:目录的 `mode: "unknown"` 是宿主明确判定的**不受支持
|
|
4581
5516
|
// 的历史条目**(宿主 `listDescendants` 映射为 diagnostic/unsupported),不能伪装成
|
|
4582
5517
|
// 普通闲置子代理——否则消费者无法区分"不受支持"与"正常闲置",等于删掉 RPC 时
|
|
4583
|
-
// 顺带静默删掉既有诊断语义(docs/
|
|
5518
|
+
// 顺带静默删掉既有诊断语义(docs/CONSOLIDATED-DOCUMENTATION.en.md Part 03 承诺 `status` 可为 diagnostic reason)。
|
|
4584
5519
|
kind: row.mode === "unknown" ? "diagnostic" : "child",
|
|
4585
5520
|
// 状态取自活 agent;已结束/已释放的子代理回落 inactive(与既有语义一致)
|
|
4586
5521
|
status: row.mode === "unknown"
|
|
@@ -4614,7 +5549,14 @@ export function apply(ctx, configInput) {
|
|
|
4614
5549
|
const childSessionId = typeof body.childSessionId === "string" ? body.childSessionId : "";
|
|
4615
5550
|
if (!parentSessionId || !childSessionId) return error(res, 400, "parentSessionId-and-childSessionId-required");
|
|
4616
5551
|
try {
|
|
4617
|
-
|
|
5552
|
+
// T-02: interruptByUser (DSH 0.2.1-rc.2+); older hosts only have interruptByParent.
|
|
5553
|
+
// The gateway adapter sends only childSessionId; the pre-gateway HTTP path keeps the full payload.
|
|
5554
|
+
try {
|
|
5555
|
+
await apiRpc("subagent.interrupt", { parentSessionId, childSessionId, mode: "continuable" });
|
|
5556
|
+
} catch (err) {
|
|
5557
|
+
if (!isEndpointUnavailable(err)) throw err;
|
|
5558
|
+
await apiRpc("subagent.interruptByParent", { parentSessionId, childSessionId, mode: "continuable" });
|
|
5559
|
+
}
|
|
4618
5560
|
sendJson(res, 200, { ok: true });
|
|
4619
5561
|
} catch (err) {
|
|
4620
5562
|
return error(res, ...rpcError(err, "subagent-interrupt-failed"));
|
|
@@ -4775,7 +5717,7 @@ export function apply(ctx, configInput) {
|
|
|
4775
5717
|
const agents = ctx.get("agents");
|
|
4776
5718
|
if (!agents) return error(res, 503, "agents-unavailable");
|
|
4777
5719
|
const sessionId = typeof body?.sessionId === "string" && body.sessionId !== "" ? body.sessionId : undefined;
|
|
4778
|
-
const agent = (sessionId ? agents.get(sessionId) : undefined) ?? agents
|
|
5720
|
+
const agent = (sessionId ? agents.get(sessionId) : undefined) ?? firstRootAgent(agents);
|
|
4779
5721
|
if (!agent) return error(res, 404, "no-live-agent");
|
|
4780
5722
|
const synthetic = {
|
|
4781
5723
|
agent,
|
|
@@ -5340,17 +6282,32 @@ export function apply(ctx, configInput) {
|
|
|
5340
6282
|
|
|
5341
6283
|
// ── 挂载与清理 ──────────────────────────────────────────────
|
|
5342
6284
|
// ── 端到端加密中继(v3.3):出站连接中继、按设备白名单放行、把手机请求回放给本机 ─────────────
|
|
5343
|
-
//
|
|
6285
|
+
// 默认允许(配置 schema 与随包补丁都指向 wss://dsh.claud.ing)。可用 = relay.enabled 且至少有一个合法的 wss:// 地址。
|
|
6286
|
+
// **按需连接(T-11)**:可用不等于连着——只有已经配对过手机、或刚生成了配对码时才去连中继;
|
|
6287
|
+
// 全新安装、从没配对过手机的电脑不产生任何中继连接(见 lib/relay/on-demand.js)。
|
|
5344
6288
|
// 连接器只出站,不开入站端口;局域网地址与口令不受影响。
|
|
5345
6289
|
const relayUrls = (config.relay?.urls ?? []).filter((u) => {
|
|
5346
6290
|
const ok = isAllowedRelayUrl(u);
|
|
5347
6291
|
if (!ok) ctx.logger.warn?.(`mobile-remote: 忽略不合法的中继地址(必须是 wss://):${u}`);
|
|
5348
6292
|
return ok;
|
|
5349
6293
|
});
|
|
6294
|
+
// 测试注入点(relayPathCheck / relayWebSocketImpl / relayTiming):生产不设。**不能直接读 `ctx.x`**:真实 cordis 的 ctx
|
|
6295
|
+
// 对没声明过的属性会抛错("cannot get property … without inject"),以前这三处直接读,在真实 DSH 上中继初始化一进来就抛、
|
|
6296
|
+
// 被下面的 catch 吞掉,中继悄悄不启用(单元测试的假 ctx 读不到只返回 undefined,所以一直没暴露)。
|
|
6297
|
+
const testHook = (name) => {
|
|
6298
|
+
try { return ctx[name]; } catch { return undefined; }
|
|
6299
|
+
};
|
|
5350
6300
|
let relay = null;
|
|
6301
|
+
// T-71 (D-01, C-15): the encrypted LAN path uses the same identity, device list and Noise
|
|
6302
|
+
// sessions as the relay, but it is free and must work with the relay switched off (D5, D20).
|
|
6303
|
+
// So the identity exists whenever the relay is allowed **or** the LAN bridge is on; only the
|
|
6304
|
+
// relay links themselves depend on relay.enabled. `relay.remote` says whether remote access
|
|
6305
|
+
// (the relay) is available; without it the connector has no links and never dials out.
|
|
6306
|
+
const relayRemote = Boolean(config.relay?.enabled) && relayUrls.length > 0;
|
|
5351
6307
|
if (config.relay?.enabled && relayUrls.length === 0) {
|
|
5352
6308
|
ctx.logger.warn?.("mobile-remote: relay.enabled 为 true 但没有合法的 relay.urls,中继未启用");
|
|
5353
|
-
}
|
|
6309
|
+
}
|
|
6310
|
+
if (relayRemote || lanEnabled) {
|
|
5354
6311
|
try {
|
|
5355
6312
|
const dir = join(mobileRemoteStateDir(), "relay");
|
|
5356
6313
|
const identity = loadOrCreateIdentity(dir, { log: (m) => ctx.logger.warn?.(`mobile-remote: ${m}`) });
|
|
@@ -5358,7 +6315,7 @@ export function apply(ctx, configInput) {
|
|
|
5358
6315
|
const connector = new RelayConnector({
|
|
5359
6316
|
identity,
|
|
5360
6317
|
devices,
|
|
5361
|
-
urls: relayUrls,
|
|
6318
|
+
urls: relayRemote ? relayUrls : [],
|
|
5362
6319
|
serve: createHttpReplayer({
|
|
5363
6320
|
port: () => ctx.webServer.port,
|
|
5364
6321
|
basePath,
|
|
@@ -5366,20 +6323,54 @@ export function apply(ctx, configInput) {
|
|
|
5366
6323
|
ipToken: bridgeIpToken,
|
|
5367
6324
|
peerHeader: RELAY_PEER_HEADER,
|
|
5368
6325
|
ipHeader: CLIENT_IP_HEADER,
|
|
5369
|
-
check:
|
|
6326
|
+
check: testHook("relayPathCheck"), // 仅测试注入;生产不设
|
|
5370
6327
|
}),
|
|
5371
|
-
WebSocketImpl:
|
|
5372
|
-
timing:
|
|
6328
|
+
WebSocketImpl: testHook("relayWebSocketImpl"), // 仅测试注入;生产不设,用全局 WebSocket(Node ≥ 22)
|
|
6329
|
+
timing: testHook("relayTiming"), // 仅测试注入(缩短超时);生产不设
|
|
5373
6330
|
log: (m) => ctx.logger.warn?.(`mobile-remote: ${m}`),
|
|
5374
6331
|
});
|
|
5375
|
-
|
|
6332
|
+
const demand = relayRemote
|
|
6333
|
+
? createRelayDemand({ connector, devices, log: (m) => ctx.logger.warn?.(`mobile-remote: ${m}`) })
|
|
6334
|
+
: { active: false, start() { return false; }, stop() {}, sync() { return false; }, dispose() {} };
|
|
6335
|
+
relay = { identity, devices, connector, demand, remote: relayRemote, urls: relayRemote ? relayUrls : [], name: config.relay?.name || hostname() };
|
|
5376
6336
|
} catch (err) {
|
|
5377
6337
|
ctx.logger.warn?.(`mobile-remote: 中继初始化失败,已关闭:${err?.message ?? err}`);
|
|
5378
6338
|
}
|
|
5379
6339
|
}
|
|
6340
|
+
// T-62 fix: after a rotation the old room keeps answering for RETIRED_ROOM_MS. A host connection
|
|
6341
|
+
// with the old key and an empty device list refuses every phone with 4401, so the revoked phone
|
|
6342
|
+
// and the ones that must pair again hear "pair again" instead of waiting for a computer that
|
|
6343
|
+
// never comes. Idle it is one quiet socket (the relay answers pings itself); it closes at the
|
|
6344
|
+
// end of the window, and on the next start an expired entry is not reopened.
|
|
6345
|
+
const retiredRooms = new Set();
|
|
6346
|
+
const openRetiredRoom = ({ identity, until }) => {
|
|
6347
|
+
if (!relay?.remote || until <= Date.now()) return;
|
|
6348
|
+
const room = new RelayConnector({
|
|
6349
|
+
identity,
|
|
6350
|
+
devices: { authorize: () => null, onRevoke: () => () => {}, list: () => [] },
|
|
6351
|
+
urls: relayUrls,
|
|
6352
|
+
serve: () => {},
|
|
6353
|
+
WebSocketImpl: testHook("relayWebSocketImpl"), // see testHook: never read ctx.x directly
|
|
6354
|
+
timing: testHook("relayTiming"),
|
|
6355
|
+
log: (m) => ctx.logger.warn?.(`mobile-remote: (old room) ${m}`),
|
|
6356
|
+
});
|
|
6357
|
+
const close = () => {
|
|
6358
|
+
clearTimeout(timer);
|
|
6359
|
+
room.stop();
|
|
6360
|
+
retiredRooms.delete(close);
|
|
6361
|
+
};
|
|
6362
|
+
const timer = setTimeout(close, Math.min(until - Date.now(), 2 ** 31 - 1));
|
|
6363
|
+
timer.unref?.();
|
|
6364
|
+
retiredRooms.add(close);
|
|
6365
|
+
room.start();
|
|
6366
|
+
};
|
|
5380
6367
|
ctx.effect(() => {
|
|
5381
|
-
relay?.
|
|
5382
|
-
|
|
6368
|
+
relay?.demand.start(); // 有已配对的手机才会真的去连;否则保持待命
|
|
6369
|
+
if (relay) for (const retired of loadRetiredIdentities(join(mobileRemoteStateDir(), "relay"))) openRetiredRoom(retired);
|
|
6370
|
+
return () => {
|
|
6371
|
+
relay?.demand.stop();
|
|
6372
|
+
for (const close of [...retiredRooms]) close();
|
|
6373
|
+
};
|
|
5383
6374
|
});
|
|
5384
6375
|
|
|
5385
6376
|
ctx.effect(() => {
|
|
@@ -5403,7 +6394,7 @@ export function apply(ctx, configInput) {
|
|
|
5403
6394
|
// 对非回环 host 直接 throw,用户 patch 也覆盖不了),手机无法直连 → 插件在 DSH 进程内
|
|
5404
6395
|
// 自建 HTTP 监听,把 `${basePath}` 前缀请求**流式**转发到回环 webserver(SSE 长连可透传)。
|
|
5405
6396
|
// 安全边界:①只转发移动端面;②`/api` 网关(桌面 GUI 内部 RPC)、`qr-config`、`qr.png`
|
|
5406
|
-
// (含 token /
|
|
6397
|
+
// (含 token / 仅本机语义)一律不转发;③口令短于 16 字符拒绝启动(LAN 暴露必须强口令;口令为空时 T-03 已改用自动生成的口令);
|
|
5407
6398
|
// ④Host 头重写为回环信任值 → 下游 hostAllowed 自然放行,真实鉴权仍由 token 把关。
|
|
5408
6399
|
// ── 启动时告诉人「手机 App 要填哪两项」(v3.2.4 零配置):地址 + 口令 ────────────
|
|
5409
6400
|
// 只打印一次:桥监听成功 / 桥启动失败或不需要桥(web 版直接用 webserver 端口)时各自触发。
|
|
@@ -5421,6 +6412,8 @@ export function apply(ctx, configInput) {
|
|
|
5421
6412
|
addresses,
|
|
5422
6413
|
token: config.authToken,
|
|
5423
6414
|
tokenIsAuto: tokenInfo.auto,
|
|
6415
|
+
// T-62: print the token only on the start that generated it.
|
|
6416
|
+
tokenNew: tokenInfo.generated === true,
|
|
5424
6417
|
tokenFile: tokenInfo.file,
|
|
5425
6418
|
persistError: tokenInfo.persistError,
|
|
5426
6419
|
authEnabled,
|
|
@@ -5430,12 +6423,10 @@ export function apply(ctx, configInput) {
|
|
|
5430
6423
|
}
|
|
5431
6424
|
};
|
|
5432
6425
|
if (lanEnabled) {
|
|
5433
|
-
|
|
5434
|
-
|
|
5435
|
-
|
|
5436
|
-
)
|
|
5437
|
-
} else if (config.authToken.length < 16) {
|
|
5438
|
-
// v2.9.0 review(B6):LAN 暴露必须 ≥16 字符强口令(与 docs/04-security §2.1 承诺一致);
|
|
6426
|
+
// T-03: with the bridge on, an empty authToken is already resolved to "@auto" (effectiveAuthSetting),
|
|
6427
|
+
// so authEnabled is always true here. The old "bridge on but no authToken" refusal could not be reached.
|
|
6428
|
+
if (config.authToken.length < 16) {
|
|
6429
|
+
// v2.9.0 review(B6):LAN 暴露必须 ≥16 字符强口令(与 docs/CONSOLIDATED-DOCUMENTATION.en.md Part 04 §2.1 承诺一致);
|
|
5439
6430
|
// 不做 schema min() 以免破坏既有用户加载——仅桥路径强制
|
|
5440
6431
|
ctx.logger.warn(
|
|
5441
6432
|
"mobile-remote: lanBridge 已启用但 authToken 短于 16 字符 —— 拒绝启动(LAN 暴露必须 ≥16 字符强随机口令)"
|
|
@@ -5473,7 +6464,7 @@ export function apply(ctx, configInput) {
|
|
|
5473
6464
|
// 只转发移动端 API 面(/m/api*);任何编码/双斜杠/大小写变体到最后都会因
|
|
5474
6465
|
// 上游 handleApi 的 rest 字面切片 ≠ 已知路由而 404;
|
|
5475
6466
|
// **qr-config 必须显式排除**(唯一回传 authToken 的端点,LAN 不可达为硬性要求,
|
|
5476
|
-
// 见 docs/
|
|
6467
|
+
// 见 docs/CONSOLIDATED-DOCUMENTATION.en.md Part 04 §3b);qr.png(不以 /m/api 开头天然排除)、
|
|
5477
6468
|
// 桌面 /api RPC 网关、/m 下其它面一律 404。
|
|
5478
6469
|
if (!pathname.startsWith(`${basePath}/api`) || pathname === `${basePath}/api/qr-config`) {
|
|
5479
6470
|
res.writeHead(404);
|
|
@@ -5575,6 +6566,24 @@ export function apply(ctx, configInput) {
|
|
|
5575
6566
|
lanServer.maxConnections = 128;
|
|
5576
6567
|
lanServer.headersTimeout = 15_000;
|
|
5577
6568
|
lanServer.requestTimeout = 180_000;
|
|
6569
|
+
// T-25:局域网加密通道。手机在桥端口上升级到 WebSocket,走与中继相同的 Noise IK + 多路复用
|
|
6570
|
+
// (relay.connector.acceptDirect)。身份靠握手里的设备密钥,不带、也不需要访问口令。
|
|
6571
|
+
// 路径是 /v1/lan,不带房间号:局域网上是明文 WebSocket,房间号是这台电脑的长期标识。
|
|
6572
|
+
// 别的路径一律 404,不升级。
|
|
6573
|
+
lanServer.on("upgrade", (req, socket, head) => {
|
|
6574
|
+
let pathname = "";
|
|
6575
|
+
try {
|
|
6576
|
+
pathname = new URL(req.url ?? "/", "http://lan").pathname;
|
|
6577
|
+
} catch {
|
|
6578
|
+
return rejectUpgrade(socket, 400, "Bad Request");
|
|
6579
|
+
}
|
|
6580
|
+
if (!relay || pathname !== "/v1/lan") return rejectUpgrade(socket, 404, "Not Found");
|
|
6581
|
+
lanBridgeSockets.add(socket);
|
|
6582
|
+
socket.once("close", () => lanBridgeSockets.delete(socket));
|
|
6583
|
+
// 一条 Noise 消息最大 65535 字节(与中继的帧上限一致)
|
|
6584
|
+
const ws = acceptWebSocket(req, socket, head, { maxPayload: 65_535 + 64 });
|
|
6585
|
+
if (ws) relay.connector.acceptDirect(ws, { ip: String(req.socket.remoteAddress ?? "") });
|
|
6586
|
+
});
|
|
5578
6587
|
lanServer.on("error", (err) => {
|
|
5579
6588
|
lanBridgeListening = false;
|
|
5580
6589
|
ctx.logger.warn(`mobile-remote: lanBridge 监听错误:${err?.message ?? err}`);
|
|
@@ -5598,10 +6607,22 @@ export function apply(ctx, configInput) {
|
|
|
5598
6607
|
if (!lanServer) announceConnection();
|
|
5599
6608
|
// webServer 守卫:纯 headless 形态(无 web 服务)下插件保持无操作,不崩进程。
|
|
5600
6609
|
const web = ctx.webServer && typeof ctx.webServer.register === "function" ? ctx.webServer : null;
|
|
6610
|
+
// T-03 (A3): DSH master makes every registered route require a DSH login (`auth` defaults to
|
|
6611
|
+
// "required": 503/401 without a Peer). The phone has no DSH login; it proves itself with our
|
|
6612
|
+
// token, so the routes opt out with "anonymous", but only while our own auth is on. With our
|
|
6613
|
+
// auth off (loopback-only), DSH's login stays in front. rc.5 ignores the extra field.
|
|
6614
|
+
// A-11: the desktop-only endpoints (`/qr-config` hands out the token, `/relay/*` pairs a phone)
|
|
6615
|
+
// answer without our token to anything that looks local, which a raw TCP tunnel or another OS
|
|
6616
|
+
// user can fake. On hosts with route auth they keep DSH's login in front ("required"; DSH's own
|
|
6617
|
+
// page has it), and localDesktopGate stays as a second layer. `/qr.png` is desktop-only too, so
|
|
6618
|
+
// it keeps the host's default. A function rule is master's WebAuthenticationRule.
|
|
6619
|
+
const apiPrefix = `${basePath}/api`;
|
|
6620
|
+
const routeAuth = authEnabled ? { auth: (request) => (isDesktopOnlyApiPath(request?.url?.pathname ?? "", apiPrefix) ? "required" : "anonymous") } : {};
|
|
5601
6621
|
const disposers = web ? [
|
|
5602
6622
|
web.register({
|
|
5603
6623
|
kind: "prefix",
|
|
5604
|
-
path:
|
|
6624
|
+
path: apiPrefix,
|
|
6625
|
+
...routeAuth,
|
|
5605
6626
|
handler: (req, res) => {
|
|
5606
6627
|
let url;
|
|
5607
6628
|
try {
|
|
@@ -5626,6 +6647,7 @@ export function apply(ctx, configInput) {
|
|
|
5626
6647
|
web.register({
|
|
5627
6648
|
kind: "exact",
|
|
5628
6649
|
path: `${basePath}/qr.png`,
|
|
6650
|
+
// A-11: desktop-only (the QR carries the token): no "anonymous", the host's default applies.
|
|
5629
6651
|
handler: (req, res) => {
|
|
5630
6652
|
let url;
|
|
5631
6653
|
try {
|
|
@@ -5648,6 +6670,8 @@ export function apply(ctx, configInput) {
|
|
|
5648
6670
|
if (!sid) return;
|
|
5649
6671
|
cancelDone(sid);
|
|
5650
6672
|
activityMap.delete(sid);
|
|
6673
|
+
// 会话没了,这轮没落地的用户发言也不该留在内存里。
|
|
6674
|
+
pendingUserText.delete(sid);
|
|
5651
6675
|
contextWindowMap.delete(sid);
|
|
5652
6676
|
titleCache.delete(sid);
|
|
5653
6677
|
lastNeedsAnswerAt.delete(sid);
|
|
@@ -5794,6 +6818,20 @@ export function apply(ctx, configInput) {
|
|
|
5794
6818
|
clearInterval(pruneTimer);
|
|
5795
6819
|
clearInterval(heldSweepTimer);
|
|
5796
6820
|
persistHeld(); // 卸载前冲刷持存排队消息
|
|
6821
|
+
// 主动调度器:停掉 tick(状态已落盘,下次启动接着算)
|
|
6822
|
+
try {
|
|
6823
|
+
proactive.stop();
|
|
6824
|
+
} catch {
|
|
6825
|
+
// 从未启动过,忽略
|
|
6826
|
+
}
|
|
6827
|
+
breakReminder.stop();
|
|
6828
|
+
// 记忆库:关闭 SQLite 句柄(WAL 才会有机会 checkpoint 回主库)。
|
|
6829
|
+
try {
|
|
6830
|
+
memoryStore?.close();
|
|
6831
|
+
} catch {
|
|
6832
|
+
// 已关闭或打不开过,忽略
|
|
6833
|
+
}
|
|
6834
|
+
memoryStore = null;
|
|
5797
6835
|
// v2.7.2 review:卸载时清理全部定时器与跟踪状态(避免对已 dispose 的 ctx 触发回调)
|
|
5798
6836
|
for (const t of deferredAskTimers) clearTimeout(t);
|
|
5799
6837
|
deferredAskTimers.clear();
|