@dsh-mobile/mobile-remote 3.4.1 → 3.5.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +1 -1
  2. package/docs/PRIVACY-POLICY.en.md +10 -2
  3. package/docs/PRIVACY-POLICY.md +10 -2
  4. package/docs/TERMS-OF-SERVICE.en.md +3 -2
  5. package/docs/TERMS-OF-SERVICE.md +3 -2
  6. package/lib/backup.js +30 -0
  7. package/lib/config.js +10 -0
  8. package/lib/host-plugins.js +290 -0
  9. package/lib/host-schedule.js +273 -0
  10. package/lib/host-team.js +89 -0
  11. package/lib/index.js +208 -3292
  12. package/lib/live-activity.js +351 -0
  13. package/lib/memory/context.js +17 -3
  14. package/lib/memory/decay.js +68 -4
  15. package/lib/memory/promises.js +116 -0
  16. package/lib/memory/routes.js +113 -1
  17. package/lib/memory/store.js +212 -13
  18. package/lib/memory/turn-hook.js +109 -0
  19. package/lib/phone-actions.js +17 -5
  20. package/lib/phone-announce.js +6 -5
  21. package/lib/phone-push.js +310 -0
  22. package/lib/protocol.js +16 -0
  23. package/lib/relay/connector.js +13 -1
  24. package/lib/routes/agents.js +405 -0
  25. package/lib/routes/app-state.js +179 -0
  26. package/lib/routes/backup.js +144 -0
  27. package/lib/routes/diagnostics.js +227 -0
  28. package/lib/routes/files.js +326 -0
  29. package/lib/routes/git.js +53 -0
  30. package/lib/routes/history.js +313 -0
  31. package/lib/routes/host-services.js +51 -0
  32. package/lib/routes/models.js +462 -0
  33. package/lib/routes/notifications.js +183 -0
  34. package/lib/routes/pairing.js +170 -0
  35. package/lib/routes/route-groups.js +20 -0
  36. package/lib/routes/send.js +341 -0
  37. package/lib/routes/sessions.js +462 -0
  38. package/lib/routes/toolbox.js +14 -0
  39. package/lib/routes/usage.js +211 -0
  40. package/lib/timeline.js +5 -1
  41. package/lib/toolbox.js +355 -0
  42. package/package.json +1 -1
@@ -0,0 +1,462 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+ import { credentialRef } from "@deepseek-ai/dsh-credentials";
9
+ import { deriveKeyRef } from "../account-usage-query.js";
10
+ import { redactPathText } from "../api-helpers.js";
11
+ import { readSettingsSection } from "../host-compat.js";
12
+ import { requireGet, requirePost, sendJson } from "../http-util.js";
13
+ import { projectionOf, rpcError } from "../rpc-adapter.js";
14
+ import { NOT_HANDLED } from "./route-groups.js";
15
+
16
+ export async function handleModelsRoutes(deps, req, res, url, rest, method, miss) {
17
+ const {
18
+ apiRpc, applyPermissionPreset, config, ctx, error, failureDetail, firstAgent, name, readJson,
19
+ readSessionConfig, removeCredential,
20
+ } = deps;
21
+
22
+ if (rest === "/catalog") {
23
+ if (requireGet(method, res)) return;
24
+
25
+ const now = Date.now();
26
+ if (url.searchParams.get("refresh") !== "1" && deps.catalogCache && now - deps.catalogCache.at < 15000) {
27
+ sendJson(res, 200, deps.catalogCache.body);
28
+ return;
29
+ }
30
+ const agents = ctx.get("agents");
31
+ const first = firstAgent(agents);
32
+ const models = [];
33
+
34
+ const reasoningEfforts = new Set();
35
+ let deploymentDefault;
36
+ const pushModels = async (provider, list) => {
37
+ for (const model of list ?? []) {
38
+ models.push({
39
+ provider,
40
+ id: model.id,
41
+ name: model.name ?? model.id,
42
+ ...(model.description === void 0 ? {} : { description: model.description }),
43
+ ...(model.contextWindow === void 0 ? {} : { contextWindow: model.contextWindow }),
44
+ ...(model.reasoning === undefined ? {} : { reasoning: {
45
+ efforts: (model.reasoning.efforts ?? []).map(({ id, name, description }) => ({ id, name, ...(description === undefined ? {} : { description }) })),
46
+ ...(model.reasoning.defaultEffort === undefined ? {} : { defaultEffort: model.reasoning.defaultEffort }),
47
+ } }),
48
+
49
+ ...(llmRef ? { imageSupported: await imageSupportedOf(provider, model.id) } : {}),
50
+ });
51
+ for (const effort of model.reasoning?.efforts ?? []) reasoningEfforts.add(effort.id);
52
+ }
53
+ };
54
+ const llmRef = ctx.get("llm");
55
+
56
+ const imageSupportedCache = new Map();
57
+ const imageSupportedOf = async (provider, modelId) => {
58
+ const key = `${provider}/${modelId}`;
59
+ if (imageSupportedCache.has(key)) return imageSupportedCache.get(key);
60
+ let ok = false;
61
+ try {
62
+ const info = await llmRef.resolveModelInfo(provider, modelId);
63
+ ok = Array.isArray(info?.inputModalities) && info.inputModalities.includes("image");
64
+ } catch {
65
+ ok = false;
66
+ }
67
+ imageSupportedCache.set(key, ok);
68
+ return ok;
69
+ };
70
+
71
+
72
+
73
+
74
+ const imageLimitsDefaults = {
75
+ maxImageBytes: 20 * 1024 * 1024,
76
+ maxImagesPerMessage: 20,
77
+ maxMessageImageBytes: 200 * 1024 * 1024,
78
+ maxImagePixels: 64e6,
79
+ maxImageDimension: 8192,
80
+ mediaTypes: ["image/png", "image/jpeg", "image/webp", "image/gif"],
81
+ };
82
+ let imageLimitsCache = { at: 0, value: null };
83
+ const imageLimitsOf = async (sessionId) => {
84
+ if (imageLimitsCache.value && Date.now() - imageLimitsCache.at < 5 * 60 * 1000) return imageLimitsCache.value;
85
+ try {
86
+ const value = await apiRpc("session.control", {}, 15000);
87
+ const limits = projectionOf(value, sessionId)?.imageLimits ?? null;
88
+ if (limits && typeof limits === "object") {
89
+ imageLimitsCache = { at: Date.now(), value: { ...imageLimitsDefaults, ...limits } };
90
+ return imageLimitsCache.value;
91
+ }
92
+ } catch {
93
+
94
+ }
95
+ return imageLimitsDefaults;
96
+ };
97
+ let providers = [];
98
+ try {
99
+ const llm = ctx.get("llm");
100
+ if (first) {
101
+ const directory = await apiRpc("session.models", { sessionId: first.id });
102
+ deploymentDefault = directory?.default;
103
+ for (const group of directory?.groups ?? []) await pushModels(group.id, group.models);
104
+ } else if (llm) {
105
+
106
+ try {
107
+ const directory = await apiRpc("session.models", {});
108
+ deploymentDefault = directory?.default;
109
+ for (const group of directory?.groups ?? []) await pushModels(group.id, group.models);
110
+ } catch {
111
+ for (const p of await llm.listProviders()) {
112
+ await pushModels(p.id, await llm.listModels(p.id));
113
+ }
114
+ }
115
+ }
116
+ if (llm) {
117
+
118
+ let registered = [];
119
+ let configurable = [];
120
+ try {
121
+ registered = await llm.listProviders();
122
+ configurable = await llm.listConfigurableProviders();
123
+ } catch {
124
+
125
+ }
126
+ const dormantIds = new Set(
127
+ configurable.filter((c) => !registered.some((r) => r.id === c.provider)).map((c) => c.provider)
128
+ );
129
+ providers = [
130
+ ...registered.map((p) => ({ id: p.id, name: p.name, dormant: false })),
131
+ ...configurable
132
+ .filter((c) => dormantIds.has(c.provider))
133
+ .map((c) => ({ id: c.provider, name: c.displayName, dormant: true })),
134
+ ];
135
+ }
136
+ } catch {
137
+
138
+ }
139
+ const permissionPresets = ctx.get("permissionPresets");
140
+
141
+
142
+ const presetSpecs = permissionPresets?.presets;
143
+ const presetEntries = presetSpecs && typeof presetSpecs === "object"
144
+ ? Object.entries(presetSpecs).map(([id, spec]) => ({ id, name: spec?.name ?? id, description: spec?.description }))
145
+ : [];
146
+ const permissionList = [
147
+ { id: "read-only", name: "Read Only", description: "只读 · 拒绝一切写入操作" },
148
+ ...presetEntries.filter((entry) => entry.id !== "read-only"),
149
+ ];
150
+ const agentPresets = [];
151
+ try {
152
+ const presets = ctx.get("agentPresets");
153
+ if (presets) {
154
+ for (const preset of await presets.list()) {
155
+ agentPresets.push({ id: preset.id, name: preset.name ?? preset.id, description: preset.description ?? "" });
156
+ }
157
+ }
158
+ } catch {
159
+
160
+ }
161
+ const defaults = {
162
+ provider: deploymentDefault?.provider,
163
+ model: deploymentDefault?.model,
164
+ reasoningEffort: deploymentDefault?.reasoningEffort,
165
+ permissionPreset: permissionPresets?.defaultSettings?.()?.defaultPreset,
166
+ agentPreset: ctx.get("agentPresets")?.defaultId,
167
+ };
168
+
169
+ const imageLimits = first ? await imageLimitsOf(first.id) : imageLimitsDefaults;
170
+ deps.catalogCache = { at: now, body: {
171
+ ok: true,
172
+ models,
173
+ providers,
174
+ reasoningEfforts: [...reasoningEfforts],
175
+ permissionPresets: permissionList,
176
+ agentPresets,
177
+ defaults,
178
+ imageLimits,
179
+ } };
180
+ sendJson(res, 200, deps.catalogCache.body);
181
+ return;
182
+ }
183
+
184
+
185
+ if (rest === "/llm-providers") {
186
+ const llm = ctx.get("llm");
187
+ if (!llm) return error(res, 503, "llm-unavailable");
188
+ const settings = ctx.get("settings");
189
+ const credentials = ctx.get("credentials");
190
+ if (method === "GET" || method === "HEAD") {
191
+ let registered = [];
192
+ let configurable = [];
193
+ try {
194
+ registered = await llm.listProviders();
195
+ configurable = await llm.listConfigurableProviders();
196
+ } catch {
197
+
198
+ }
199
+ const rows = [];
200
+ const seen = new Set();
201
+ for (const p of registered) {
202
+ rows.push({ id: p.id, name: p.name, dormant: false, settingsNs: null, settingsPath: [], baseURL: null, apiKeyRef: null, keyConfigured: false, keyWritable: false, catalogModels: null });
203
+ seen.add(p.id);
204
+ }
205
+ for (const c of configurable) {
206
+ const row = rows.find((r) => r.id === c.provider);
207
+ const entry = row ?? { id: c.provider, name: c.displayName, dormant: true, settingsNs: c.settingsNs, settingsPath: c.settingsPath ?? [], baseURL: null, apiKeyRef: null, keyConfigured: false, keyWritable: false, catalogModels: null };
208
+ entry.settingsNs = c.settingsNs;
209
+ entry.settingsPath = c.settingsPath ?? [];
210
+ if (settings && entry.settingsNs) {
211
+ try {
212
+
213
+
214
+ const section = readSettingsSection(settings, entry.settingsNs);
215
+ let prof = section;
216
+ for (const k of entry.settingsPath) prof = prof?.[k];
217
+ if (prof && typeof prof === "object") {
218
+ entry.baseURL = typeof prof.baseURL === "string" ? prof.baseURL : null;
219
+ entry.apiKeyRef = typeof prof.apiKeyEnv === "string" && prof.apiKeyEnv !== "" ? prof.apiKeyEnv : null;
220
+ entry.catalogModels = Array.isArray(prof.models)
221
+ ? prof.models.map((m) => ({ id: m.id, name: m.name ?? m.id }))
222
+ : null;
223
+ }
224
+ } catch {
225
+
226
+ }
227
+ }
228
+ if (credentials && entry.apiKeyRef) {
229
+ try {
230
+ const info = await credentials.describe(credentialRef(entry.apiKeyRef));
231
+ entry.keyConfigured = info?.configured ?? false;
232
+ entry.keyWritable = info?.writable ?? false;
233
+ } catch {
234
+
235
+ }
236
+ }
237
+ if (row) Object.assign(row, entry);
238
+ else rows.push(entry);
239
+ }
240
+ sendJson(res, 200, { ok: true, providers: rows });
241
+ return;
242
+ }
243
+ if (method === "POST") {
244
+ const body = await readJson(req, res);
245
+ if (body === undefined) return;
246
+ const provider = typeof body.provider === "string" ? body.provider : "";
247
+ const ns = typeof body.settingsNs === "string" ? body.settingsNs : "";
248
+ const baseURL = typeof body.baseURL === "string" ? body.baseURL.trim() : "";
249
+ const apiKey = typeof body.apiKey === "string" ? body.apiKey.trim() : "";
250
+
251
+ let configurable = [];
252
+ try {
253
+ configurable = await llm.listConfigurableProviders();
254
+ } catch {
255
+
256
+ }
257
+ const dir = configurable.find((c) => c.provider === provider && c.settingsNs === ns);
258
+ if (!dir) return error(res, 400, "unknown-provider", "提供商不在可配置目录中");
259
+ if (!settings) return error(res, 503, "settings-unavailable");
260
+ if (baseURL === "") return error(res, 400, "baseURL-required");
261
+ const path = dir.settingsPath ?? [];
262
+
263
+ let ref = null;
264
+ let existingProfile = null;
265
+ try {
266
+
267
+ const section = readSettingsSection(settings, ns);
268
+ let prof = section;
269
+ for (const k of path) prof = prof?.[k];
270
+ if (prof && typeof prof === "object") {
271
+ existingProfile = prof;
272
+ if (typeof prof.apiKeyEnv === "string" && prof.apiKeyEnv !== "") ref = prof.apiKeyEnv;
273
+ }
274
+ } catch {}
275
+
276
+ const normalizeModels = (list) =>
277
+ list
278
+ .map((m) =>
279
+ typeof m === "string"
280
+ ? { id: m }
281
+ : { id: String(m?.id ?? ""), ...(typeof m?.name === "string" && m.name !== "" ? { name: m.name } : {}) }
282
+ )
283
+ .filter((m) => m.id !== "");
284
+ const models = Array.isArray(body.models) && body.models.length > 0 ? normalizeModels(body.models) : null;
285
+ let ops;
286
+ let keyRemovalError = false;
287
+
288
+
289
+ try {
290
+ if (path.length === 0) {
291
+
292
+ ops = [{ op: "set", path: ["baseURL"], value: baseURL }];
293
+ if (models) ops.push({ op: "set", path: ["models"], value: models });
294
+ if (apiKey !== "" || body.removeKey === true) {
295
+ if (!credentials) return error(res, 503, "credentials-unavailable");
296
+ ref = ref ?? deriveKeyRef(provider);
297
+ ops.push({ op: "set", path: ["apiKeyEnv"], value: ref });
298
+ if (apiKey !== "") await credentials.set(credentialRef(ref), apiKey);
299
+ else keyRemovalError = await removeCredential(credentials, ref);
300
+ }
301
+ } else {
302
+
303
+ if (apiKey !== "" || body.removeKey === true) {
304
+ if (!credentials) return error(res, 503, "credentials-unavailable");
305
+ ref = ref ?? deriveKeyRef(provider);
306
+ if (apiKey !== "") await credentials.set(credentialRef(ref), apiKey);
307
+ else keyRemovalError = await removeCredential(credentials, ref);
308
+ }
309
+ const profile = {
310
+ ...(existingProfile && typeof existingProfile === "object" ? existingProfile : {}),
311
+ ...(typeof body.displayName === "string" && body.displayName !== "" ? { displayName: body.displayName } : {}),
312
+ ...(typeof body.api === "string" && body.api !== "" ? { api: body.api } : {}),
313
+ baseURL,
314
+ ...(models ? { models } : {}),
315
+ };
316
+ if (apiKey !== "" || body.removeKey === true) {
317
+ if (apiKey !== "") profile.apiKeyEnv = ref;
318
+ else delete profile.apiKeyEnv;
319
+ }
320
+ ops = [{ op: "set", path, value: profile }];
321
+ }
322
+ await settings.mutate(ns, ops);
323
+ } catch (err) {
324
+ ctx.logger.warn(`mobile-remote: llm-providers 写入失败:${err?.message ?? err}`);
325
+ return error(res, err?.status ?? 400, "provider-write-failed", failureDetail(err));
326
+ }
327
+
328
+
329
+ sendJson(res, 200, { ok: true, provider, apiKeyRef: ref, keyConfigured: apiKey !== "", ...(keyRemovalError ? { keyRemovalError: true } : {}) });
330
+ return;
331
+ }
332
+ return error(res, 405, "method-not-allowed");
333
+ }
334
+
335
+ if (rest === "/llm-providers/probe") {
336
+ if (requirePost(method, res)) return;
337
+ const llm = ctx.get("llm");
338
+ if (!llm) return error(res, 503, "llm-unavailable");
339
+ const body = await readJson(req, res);
340
+ if (body === undefined) return;
341
+ const ns = typeof body.settingsNs === "string" ? body.settingsNs : "";
342
+ const baseURL = typeof body.baseURL === "string" ? body.baseURL.trim() : "";
343
+ const apiKey = typeof body.apiKey === "string" ? body.apiKey.trim() : "";
344
+ if (ns === "" || baseURL === "") return error(res, 400, "bad-request", "settingsNs 与 baseURL 必填");
345
+
346
+ let configurable = [];
347
+ try {
348
+ configurable = await llm.listConfigurableProviders();
349
+ } catch {
350
+
351
+ }
352
+ if (!configurable.some((c) => c.settingsNs === ns)) return error(res, 400, "unknown-namespace");
353
+ try {
354
+ let discovered = null;
355
+ let usedFallback = false;
356
+ try {
357
+ discovered = await llm.discoverModels(ns, {
358
+ baseURL,
359
+ ...(typeof body.protocol === "string" && body.protocol !== "" ? { protocol: body.protocol } : {}),
360
+ ...(apiKey !== "" ? { credential: apiKey } : {}),
361
+ });
362
+ } catch (err) {
363
+
364
+
365
+ if (String(err?.message ?? err).includes("no model discovery")) {
366
+ usedFallback = true;
367
+ const headers = { accept: "application/json", ...(apiKey !== "" ? { authorization: `Bearer ${apiKey}` } : {}) };
368
+ const resp = await fetch(`${baseURL.replace(/\/+$/, "")}/models`, { headers, signal: AbortSignal.timeout(10_000) });
369
+ if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
370
+ const j = await resp.json();
371
+ discovered = (Array.isArray(j?.data) ? j.data : []).map((m) => ({
372
+ id: typeof m.id === "string" ? m.id : String(m.id ?? ""),
373
+ ...(typeof m.name === "string" ? { name: m.name } : {}),
374
+ ...(typeof m.contextWindow === "number" ? { contextWindow: m.contextWindow } : {}),
375
+ }));
376
+ } else {
377
+ throw err;
378
+ }
379
+ }
380
+ sendJson(res, 200, { ok: true, models: discovered ?? [], fallback: usedFallback });
381
+ } catch (err) {
382
+ const raw = String(err?.message ?? err);
383
+
384
+ const friendly =
385
+ /(^|\s)(401|403)\b|answered 401|answered 403|HTTP 401|HTTP 403/.test(raw)
386
+ ? "API Key 无效或未填写:请在该条目填入有效的 API Key 后重试(探测不会携带已保存的密钥);DeepSeek 官方模型内置可用,无需探测"
387
+ : /could not reach|fetch failed|ENOTFOUND|ECONNREFUSED|ECONNRESET|ERR_CONNECTION|ERR_SOCKET|ETIMEDOUT|timed out|timeout/i.test(raw)
388
+ ? "无法连接该端点:请检查网络与 baseURL(需以 http:// 或 https:// 开头并含主机名,如 https://api.deepseek.com)"
389
+ : /404|not found/i.test(raw)
390
+ ? "该端点没有 /models 接口(HTTP 404):请确认 baseURL 为该服务的 API 根地址,或改用手动输入模型"
391
+ : null;
392
+
393
+ return error(res, 400, "probe-failed", redactPathText(friendly ? `${friendly}(原始错误:${raw})` : raw));
394
+ }
395
+ return;
396
+ }
397
+
398
+ if (rest === "/session-config") {
399
+ let sessionId = url.searchParams.get("sessionId");
400
+ let body;
401
+ if (method === "POST") {
402
+ body = await readJson(req, res);
403
+ if (body === undefined) return;
404
+ if (typeof body?.sessionId === "string") sessionId = body.sessionId;
405
+ }
406
+ if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
407
+ if (method === "GET" || method === "HEAD") {
408
+ const config = await readSessionConfig(sessionId);
409
+ sendJson(res, 200, { ok: true, sessionId, config });
410
+ return;
411
+ }
412
+ if (method === "POST") {
413
+ const sessions = ctx.get("sessions");
414
+ const session = sessions?.get(sessionId);
415
+ const modelConfigPatch = body.model !== undefined || body.provider !== undefined || body.reasoningEffort !== undefined || body.resetReasoningEffort !== undefined;
416
+
417
+
418
+ if (!session && (!modelConfigPatch || body.permissionPreset !== undefined)) return error(res, 404, "session-not-found");
419
+ if (modelConfigPatch) {
420
+ if (body.resetReasoningEffort !== undefined && body.resetReasoningEffort !== true) return error(res, 400, "bad-request", "invalid resetReasoningEffort");
421
+ if (body.resetReasoningEffort === true && body.reasoningEffort !== undefined) return error(res, 400, "bad-request", "choose effort or reset, not both");
422
+ const explicitModel = body.model !== undefined || body.provider !== undefined;
423
+ if (explicitModel && (typeof body.provider !== "string" || !body.provider || typeof body.model !== "string" || !body.model)) {
424
+ return error(res, 400, "bad-request", "provider and model required together");
425
+ }
426
+ if (body.reasoningEffort !== undefined && (typeof body.reasoningEffort !== "string" || !body.reasoningEffort)) {
427
+ return error(res, 400, "bad-request", "invalid reasoningEffort");
428
+ }
429
+
430
+ const current = explicitModel ? undefined : await readSessionConfig(sessionId);
431
+ const provider = explicitModel ? body.provider : current?.provider;
432
+ const model = explicitModel ? body.model : current?.model;
433
+ if (!provider || !model) return error(res, 409, "model-selection-unavailable", "无法确认待生效模型,请重新选择模型");
434
+ try {
435
+ await apiRpc("session.selectModel", {
436
+ sessionId, provider, model,
437
+
438
+ ...(body.reasoningEffort === undefined ? {} : { reasoningEffort: body.reasoningEffort }),
439
+ });
440
+ } catch (err) {
441
+ return error(res, ...rpcError(err, "model-select-failed"));
442
+ }
443
+ }
444
+ if (body.permissionPreset !== undefined) {
445
+ if (body.permissionPreset === "danger-full-access" && body.confirmDanger !== true) {
446
+ return error(res, 400, "risk-confirmation-required", "选择完全访问需显式确认风险");
447
+ }
448
+ try {
449
+ applyPermissionPreset(session, body.permissionPreset);
450
+ } catch (err) {
451
+ return error(res, err.status ?? 400, "permission-apply-failed", err.message);
452
+ }
453
+ }
454
+ const config = await readSessionConfig(sessionId);
455
+ sendJson(res, 200, { ok: true, sessionId, config });
456
+ return;
457
+ }
458
+ return error(res, 405, "method-not-allowed");
459
+ }
460
+ miss.now = true;
461
+ return NOT_HANDLED;
462
+ }
@@ -0,0 +1,183 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+ import { validateQuestionAnswers } from "../api-helpers.js";
9
+ import { requireGet, requirePost, sendJson } from "../http-util.js";
10
+ import { NOT_HANDLED } from "./route-groups.js";
11
+
12
+ export async function handleNotificationsRoutes(deps, req, res, url, rest, method, miss) {
13
+ const {
14
+ NOTIF_MAX, broadcast, config, ctx, error, finishApproval, finishQuestion, mobileActions, notifStore,
15
+ pendingApprovals, pendingQuestions, pushTracked, questionCancelledError, readIds, readJson,
16
+ scheduleReadPersist,
17
+ } = deps;
18
+ if (rest === "/notifications") {
19
+ if (requireGet(method, res)) return;
20
+ const items = [...notifStore.values()]
21
+ .sort((a, b) => b.time - a.time)
22
+ .map((n) => ({ ...n, unread: !readIds.has(n.id) }));
23
+ sendJson(res, 200, { ok: true, unread: items.filter((n) => n.unread).length, items: items.slice(0, NOTIF_MAX) });
24
+ return;
25
+ }
26
+
27
+ if (rest === "/notifications/read") {
28
+ if (requirePost(method, res)) return;
29
+ const body = await readJson(req, res);
30
+ if (body === undefined) return;
31
+ if (body?.all === true) {
32
+ for (const id of notifStore.keys()) readIds.add(id);
33
+ } else if (Array.isArray(body?.ids)) {
34
+
35
+
36
+ for (const id of body.ids.slice(0, 500)) {
37
+ const s = String(id);
38
+ if (notifStore.has(s)) readIds.add(s);
39
+ }
40
+ } else {
41
+ return error(res, 400, "bad-request", "expected { ids } or { all: true }");
42
+ }
43
+ scheduleReadPersist();
44
+ sendJson(res, 200, { ok: true });
45
+ return;
46
+ }
47
+
48
+ if (rest === "/notifications/delete") {
49
+ if (requirePost(method, res)) return;
50
+ const body = await readJson(req, res);
51
+ if (body === undefined) return;
52
+
53
+
54
+ if (body?.all === true) {
55
+ for (const id of notifStore.keys()) readIds.delete(id);
56
+ notifStore.clear();
57
+ } else if (Array.isArray(body?.ids)) {
58
+
59
+ for (const id of body.ids.slice(0, 500)) {
60
+ notifStore.delete(String(id));
61
+ readIds.delete(String(id));
62
+ }
63
+ } else {
64
+ return error(res, 400, "bad-request", "expected { ids } or { all: true }");
65
+ }
66
+ scheduleReadPersist();
67
+ broadcast({ type: "notifications/changed" });
68
+ sendJson(res, 200, { ok: true });
69
+ return;
70
+ }
71
+
72
+ if (rest === "/push-test") {
73
+
74
+
75
+ if (requirePost(method, res)) return;
76
+ const results = [];
77
+ for (const target of config.pushUrls) {
78
+ const outcome = await pushTracked(target, "test", "🔔 测试通知", "配置验证", "收到即说明该通道配置正确(来自 DSH Remote)", "");
79
+ results.push({ name: target.name, format: target.format, ok: outcome.ok, ...(outcome.ok ? {} : { error: outcome.error }) });
80
+ }
81
+ sendJson(res, 200, { ok: true, channels: results.length, results });
82
+ return;
83
+ }
84
+
85
+ if (rest === "/respond") {
86
+
87
+
88
+
89
+
90
+
91
+
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+ if (requirePost(method, res)) return;
101
+ const body = await readJson(req, res);
102
+ if (body === undefined) return;
103
+ const rpcId = typeof body?.rpcId === "string" ? body.rpcId : "";
104
+
105
+
106
+
107
+ const claimedSessionId = typeof body?.sessionId === "string" ? body.sessionId : "";
108
+ const sessionOwns = (entry) => {
109
+ if (claimedSessionId === "") {
110
+ ctx.logger.warn?.(`mobile-remote: /respond 缺少 sessionId(宽容接受,请升级 App):kind=${body?.kind} rpcId=${rpcId}`);
111
+ return true;
112
+ }
113
+ return claimedSessionId === entry.sessionId;
114
+ };
115
+ if (body?.kind === "question") {
116
+ const qPhoneId = typeof body?.questionId === "string" ? body.questionId : "";
117
+ const qById = qPhoneId === "" ? undefined : pendingQuestions.get(qPhoneId);
118
+ const qByRpc = rpcId === "" ? undefined : [...pendingQuestions.values()].find((e) => e.rpcId === rpcId);
119
+
120
+ if (qById && qByRpc && qById !== qByRpc) return error(res, 400, "interaction-mismatch", "questionId 与 rpcId 指向不同问询");
121
+ const qEntry = qById ?? qByRpc;
122
+ if (qEntry) {
123
+ if (!sessionOwns(qEntry)) return error(res, 400, "session-mismatch", "问询不属于该会话");
124
+ if (!Array.isArray(body?.answers)) return error(res, 400, "bad-request", "question respond expects answers[]");
125
+ if (!Array.isArray(qEntry.questions) || qEntry.questions.length === 0) {
126
+
127
+
128
+ ctx.logger.warn?.(`mobile-remote: /respond 待办条目缺少 questions(${qEntry.phoneId}),answer 无法校验`);
129
+ }
130
+ const validation = validateQuestionAnswers(qEntry.questions, body.answers);
131
+ if (!validation.ok) return error(res, 400, validation.code, validation.detail);
132
+ finishQuestion(qEntry, { answers: body.answers });
133
+ sendJson(res, 200, { ok: true, accepted: true });
134
+ return;
135
+ }
136
+ if (!Array.isArray(body?.answers)) return error(res, 400, "bad-request", "question respond expects answers[]");
137
+ } else if (body?.kind === "approval") {
138
+ const outcome = typeof body?.outcome === "string" ? body.outcome : "";
139
+ const aPhoneId = typeof body?.approvalId === "string" ? body.approvalId : "";
140
+ const aById = aPhoneId === "" ? undefined : pendingApprovals.get(aPhoneId);
141
+ const aByRpc = rpcId === "" ? undefined : [...pendingApprovals.values()].find((e) => e.rpcId === rpcId);
142
+ if (aById && aByRpc && aById !== aByRpc) return error(res, 400, "interaction-mismatch", "approvalId 与 rpcId 指向不同审批");
143
+ const aEntry = aById ?? aByRpc;
144
+ if (aEntry) {
145
+ if (!sessionOwns(aEntry)) return error(res, 400, "session-mismatch", "审批不属于该会话");
146
+
147
+
148
+
149
+ if (outcome !== "allowed-once" && outcome !== "rejected") {
150
+ return error(res, 400, "approval-outcome-invalid", "outcome 必须是 allowed-once | rejected");
151
+ }
152
+ finishApproval(aEntry, outcome);
153
+ sendJson(res, 200, { ok: true, accepted: true });
154
+ return;
155
+ }
156
+ } else if (body?.kind === "cancel") {
157
+
158
+
159
+
160
+ const cancelEntry = [...pendingApprovals.values()].find((e) => e.rpcId === rpcId)
161
+ ?? [...pendingQuestions.values()].find((e) => e.rpcId === rpcId);
162
+ if (cancelEntry) {
163
+ if (!sessionOwns(cancelEntry)) return error(res, 400, "session-mismatch", "待办不属于该会话");
164
+ if (pendingApprovals.has(cancelEntry.phoneId)) finishApproval(cancelEntry, "cancelled");
165
+ else finishQuestion(cancelEntry, questionCancelledError(), { reject: true });
166
+ sendJson(res, 200, { ok: true, accepted: true });
167
+ return;
168
+ }
169
+ }
170
+
171
+
172
+
173
+ return error(res, 404, "respond-not-pending", "该待办不在本地清单中(可能已由另一端先答,或已超时)");
174
+ }
175
+
176
+ if (rest === "/actions") {
177
+ if (requireGet(method, res)) return;
178
+ sendJson(res, 200, { ok: true, actions: mobileActions.list() });
179
+ return;
180
+ }
181
+ miss.now = true;
182
+ return NOT_HANDLED;
183
+ }