@dsh-mobile/mobile-remote 3.4.1-beta.2 → 3.5.0-beta.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.
@@ -0,0 +1,170 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+ import { join } from "node:path";
9
+ import QRCode from "qrcode";
10
+ import { mobileRemoteStateDir, rotateAuthToken } from "../auto-config.js";
11
+ import { requireGet, requirePost, sendJson } from "../http-util.js";
12
+ import { b64u as relayB64u } from "../relay/crypto.js";
13
+ import { pairingFingerprint as pairingFingerprintOf } from "../relay/fingerprint.js";
14
+ import { RETIRED_ROOM_MS, retireIdentity, rotateIdentity } from "../relay/identity.js";
15
+ import { buildPairingUri } from "../relay/pairing.js";
16
+ import { NOT_HANDLED } from "./route-groups.js";
17
+
18
+ export async function handlePairingRoutes(deps, req, res, url, rest, method, miss) {
19
+ const {
20
+ authEnabled, basePath, config, connections, ctx, dropConn, error, ipv4Addresses, lanNoiseUrls, lanPort,
21
+ localDesktopGate, openRetiredRoom, privateFirst, readJson, tokenInfo,
22
+ } = deps;
23
+ if (rest === "/qr-config") {
24
+
25
+
26
+
27
+
28
+ if (requireGet(method, res)) return;
29
+ const gate = localDesktopGate(req);
30
+ if (!gate.ok) return error(res, 403, gate.code, gate.detail);
31
+
32
+
33
+ const qrUrls = deps.lanBridgeListening
34
+ ? [...privateFirst(ipv4Addresses())].map((ip) => `http://${ip}:${lanPort}${basePath}`)
35
+ : [...privateFirst(ipv4Addresses()), "127.0.0.1"].map((ip) => `http://${ip}:${ctx.webServer.port}${basePath}`);
36
+ sendJson(res, 200, {
37
+ ok: true,
38
+ urls: qrUrls,
39
+ token: config.authToken,
40
+ path: basePath,
41
+ });
42
+ return;
43
+ }
44
+
45
+
46
+ if (rest === "/relay/status") {
47
+ if (requireGet(method, res)) return;
48
+ const gate = localDesktopGate(req);
49
+ if (!gate.ok) return error(res, 403, gate.code, gate.detail);
50
+ sendJson(res, 200, {
51
+ ok: true,
52
+
53
+
54
+ enabled: deps.relay?.remote === true,
55
+ lanNoise: lanNoiseUrls().length > 0,
56
+ ...(deps.relay
57
+ ? {
58
+
59
+ standby: !deps.relay.demand.active,
60
+ roomId: deps.relay.identity.roomId,
61
+ publicKey: relayB64u.enc(deps.relay.identity.x.pub),
62
+ relays: deps.relay.connector.status(),
63
+ devices: deps.relay.devices.list(),
64
+ pendingPairings: deps.relay.devices.pendingPairings(),
65
+ }
66
+ : {}),
67
+ });
68
+ return;
69
+ }
70
+ if (rest === "/relay/pairing") {
71
+ if (requirePost(method, res)) return;
72
+ const gate = localDesktopGate(req);
73
+ if (!gate.ok) return error(res, 403, gate.code, gate.detail);
74
+ const body = await readJson(req, res, 4096);
75
+ if (body === undefined) return;
76
+
77
+
78
+
79
+ const lanOnly = body?.mode === "lan";
80
+ if (lanOnly) {
81
+ if (!deps.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)");
82
+ } else if (!deps.relay?.remote) {
83
+ return error(res, 409, "relay-disabled", "未启用中继:在 cordis.patch.yml 的 mobile-remote 配置里设置 relay.enabled 与 relay.urls");
84
+ }
85
+
86
+ if (deps.relay.rotating) return error(res, 409, "relay-rotating", "正在更换中继密钥,请稍后再试 / the relay key is being replaced; try again in a moment");
87
+ const { otp, expiresAt } = deps.relay.devices.createPairing(typeof body?.deviceName === "string" ? body.deviceName : undefined, { relay: !lanOnly });
88
+ deps.relay.demand.sync();
89
+
90
+ const uri = buildPairingUri({ relays: lanOnly ? [] : deps.relay.urls, roomId: deps.relay.identity.roomId, pcPub: deps.relay.identity.x.pub, otp, name: deps.relay.name, lan: lanNoiseUrls() });
91
+ const qr = await QRCode.toDataURL(uri, { width: 512, margin: 1, errorCorrectionLevel: "M" });
92
+
93
+
94
+
95
+ const fingerprint = pairingFingerprintOf(deps.relay.identity.x.pub);
96
+
97
+ sendJson(res, 200, { ok: true, uri, qr, fingerprint, expiresAt }, { "cache-control": "no-store" });
98
+ return;
99
+ }
100
+ if (rest === "/relay/revoke") {
101
+ if (requirePost(method, res)) return;
102
+ const gate = localDesktopGate(req);
103
+ if (!gate.ok) return error(res, 403, gate.code, gate.detail);
104
+ if (!deps.relay) return error(res, 409, "relay-disabled", "未启用中继");
105
+ const body = await readJson(req, res, 1024);
106
+ if (body === undefined) return;
107
+ if (typeof body?.id !== "string" || body.id === "") return error(res, 400, "bad-request", "缺少设备 id");
108
+ if (deps.relay.rotating) return error(res, 409, "relay-rotating", "正在更换中继密钥,请稍后再试 / the relay key is being replaced; try again in a moment");
109
+ if (!deps.relay.devices.list().some((d) => d.id === body.id)) return sendJson(res, 200, { ok: true, revoked: false });
110
+
111
+
112
+
113
+
114
+
115
+
116
+
117
+
118
+
119
+
120
+
121
+ const result = { ok: true, revoked: false, relayKeyRotated: false, tokenRotated: false, repairRequired: 0 };
122
+ deps.relay.rotating = true;
123
+ try {
124
+ deps.relay.devices.cancelPairings();
125
+ result.revoked = deps.relay.devices.revoke(body.id);
126
+ for (const device of deps.relay.devices.list()) {
127
+ if (deps.relay.devices.revoke(device.id)) result.repairRequired += 1;
128
+ }
129
+ deps.relay.demand?.sync();
130
+ const acknowledged = await deps.relay.connector.settled();
131
+ if (!acknowledged) ctx.logger.warn("mobile-remote: the relay did not confirm every disconnect in time; rotating anyway");
132
+ deps.relay.connector.stop();
133
+
134
+ const until = Date.now() + RETIRED_ROOM_MS;
135
+ retireIdentity(join(mobileRemoteStateDir(), "relay"), deps.relay.identity, until);
136
+ openRetiredRoom({ identity: deps.relay.identity, until });
137
+ const next = rotateIdentity(join(mobileRemoteStateDir(), "relay"));
138
+ deps.relay.connector.identity = next;
139
+ deps.relay.identity = next;
140
+ result.relayKeyRotated = true;
141
+ if (deps.relay.demand) deps.relay.demand.sync();
142
+ else deps.relay.connector.start();
143
+ } catch (err) {
144
+ ctx.logger.warn(`mobile-remote: relay key rotation after revoke failed: ${err?.message ?? err}`);
145
+ } finally {
146
+ deps.relay.rotating = false;
147
+ }
148
+ if (tokenInfo.auto) {
149
+ try {
150
+ config.authToken = rotateAuthToken().token;
151
+ result.tokenRotated = true;
152
+
153
+
154
+
155
+ for (const conn of [...connections]) if (conn.dshVia === "token") dropConn(conn);
156
+ } catch (err) {
157
+ ctx.logger.warn(`mobile-remote: access token rotation after revoke failed: ${err?.message ?? err}`);
158
+ }
159
+ } else if (authEnabled) {
160
+ result.tokenRotationSkipped = "configured";
161
+ ctx.logger.warn(
162
+ "mobile-remote: a device was revoked; change authToken in your config, it may still be on that phone / 已撤销设备:请在配置里更换 authToken,旧口令可能还在那台手机上",
163
+ );
164
+ }
165
+ sendJson(res, 200, result);
166
+ return;
167
+ }
168
+ miss.now = true;
169
+ return NOT_HANDLED;
170
+ }
@@ -0,0 +1,20 @@
1
+
2
+ export const NOT_HANDLED = Symbol("not-handled");
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+ export async function runRouteGroups(groups, deps, req, res, url, rest, method) {
12
+ for (const group of groups) {
13
+ const miss = { now: false };
14
+ const result = group(deps, req, res, url, rest, method, miss);
15
+ if (miss.now) continue;
16
+
17
+ if ((await result) !== NOT_HANDLED) return true;
18
+ }
19
+ return false;
20
+ }
@@ -0,0 +1,341 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
9
+ import { receiptExpired } from "../api-helpers.js";
10
+ import { firstRootAgent } from "../host-compat.js";
11
+ import { guardRes, requireGet, requirePost, sendJson } from "../http-util.js";
12
+ import { rpcError } from "../rpc-adapter.js";
13
+ import { sniffImageType } from "../timeline.js";
14
+ import { NOT_HANDLED } from "./route-groups.js";
15
+
16
+ export async function handleSendRoutes(deps, req, res, url, rest, method, miss) {
17
+ const {
18
+ DROP_RESPONSE_HOOK, RECEIPT_TTL, apiRpc, broadcastQueue, ctx, error, failureDetail, heldContentOf, heldOf,
19
+ heldQueue, persistHeld, persistReceipts, promptImage, pruneReceipts, queueRowsOf, readJson, receiptKeyOf,
20
+ resumeDormantAgent, sendReceipts,
21
+ } = deps;
22
+ if (rest === "/send") {
23
+ if (requirePost(method, res)) return;
24
+
25
+
26
+
27
+ const declaredLength = Number(req.headers["content-length"]);
28
+ if (Number.isFinite(declaredLength) && declaredLength > 64 * 1024 * 1024) {
29
+ return error(res, 413, "payload-too-large", "request body exceeds 64MB limit");
30
+ }
31
+ const body = await readJson(req, res, 64 * 1024 * 1024);
32
+ if (body === undefined) return;
33
+ const text = typeof body?.text === "string" ? body.text : "";
34
+
35
+
36
+
37
+
38
+ const images = Array.isArray(body?.images)
39
+ ? body.images.slice(0, 20)
40
+ .filter((im) => im && typeof im?.data === "string" && im.data !== "" && typeof im?.mediaType === "string")
41
+ .map((im) => {
42
+ const real = sniffImageType(im.data);
43
+ if (real && real !== im.mediaType) {
44
+ ctx.logger.warn?.(`mobile-remote: /send 图片类型纠正 ${im.mediaType} → ${real}(声明与字节不符,按字节纠正)`);
45
+ return { ...im, mediaType: real };
46
+ }
47
+ return im;
48
+ })
49
+ : [];
50
+ if (text.trim() === "" && images.length === 0) return error(res, 400, "empty-text");
51
+
52
+ const requestId = typeof body?.requestId === "string" && body.requestId !== "" ? body.requestId : undefined;
53
+ if (requestId !== undefined && !/^[A-Za-z0-9-]{8,64}$/.test(requestId)) {
54
+ return error(res, 400, "bad-request", "invalid requestId");
55
+ }
56
+
57
+
58
+
59
+
60
+
61
+ const steer = body?.mode === "steer";
62
+ const agents = ctx.get("agents");
63
+ if (!agents) return error(res, 503, "agents-unavailable");
64
+ const sessionId = typeof body?.sessionId === "string" && body.sessionId ? body.sessionId : undefined;
65
+ let target = sessionId ? agents.get(sessionId) : firstRootAgent(agents);
66
+
67
+ let configDegraded = false;
68
+ if (!target && sessionId) {
69
+
70
+
71
+ const resumed = await resumeDormantAgent(sessionId);
72
+ if (resumed) {
73
+ target = resumed.agent;
74
+ configDegraded = configDegraded || resumed.configDegraded;
75
+ }
76
+ }
77
+ if (!target) return error(res, sessionId ? 404 : 503, sessionId ? "session-not-found" : "no-live-agent");
78
+ const receiptKey = requestId ? receiptKeyOf(sessionId, target.id, requestId) : null;
79
+ if (receiptKey) {
80
+
81
+ if (pruneReceipts()) persistReceipts();
82
+ let existing = sendReceipts.get(receiptKey);
83
+ if (existing && receiptExpired(existing.at, Date.now(), RECEIPT_TTL)) {
84
+
85
+
86
+ sendReceipts.delete(receiptKey);
87
+ persistReceipts();
88
+ existing = undefined;
89
+ }
90
+ if (existing) {
91
+ if (existing.status === "done" || existing.status === "error") {
92
+
93
+ return sendJson(res, 200, existing.result ?? { ok: true });
94
+ }
95
+ return error(res, 409, "receipt-pending", "同一请求正在处理中");
96
+ }
97
+ sendReceipts.set(receiptKey, { status: "in-progress", result: null, at: Date.now() });
98
+ persistReceipts();
99
+ }
100
+
101
+
102
+
103
+ const finalize = (res, status, resultBody) => {
104
+ if (receiptKey) {
105
+ sendReceipts.delete(receiptKey);
106
+ sendReceipts.set(receiptKey, { status: status >= 400 ? "error" : "done", result: resultBody, at: Date.now() });
107
+ pruneReceipts();
108
+ persistReceipts();
109
+ }
110
+ if (DROP_RESPONSE_HOOK) {
111
+ guardRes(res);
112
+ res.destroy();
113
+ return;
114
+ }
115
+ sendJson(res, status, configDegraded ? { ...resultBody, configDegraded: true } : resultBody);
116
+ };
117
+
118
+
119
+ const content = text.trim() !== ""
120
+ ? [{ type: "text", text }, ...images.map((im) => ({ type: "image", mediaType: im.mediaType, data: im.data, ...(typeof im.name === "string" && im.name !== "" ? { name: im.name } : {}) }))]
121
+ : images.map((im) => ({ type: "image", mediaType: im.mediaType, data: im.data, ...(typeof im.name === "string" && im.name !== "" ? { name: im.name } : {}) }));
122
+ const hasImages = images.length > 0;
123
+
124
+ ctx.logger.info?.(`mobile-remote: /send hit → ${target.id} text=${text.length}B imgs=${images.length} steer=${steer} status=${target.status}`);
125
+ const prompt = (mode) => promptImage(target.id, mode, content);
126
+
127
+
128
+
129
+ let message;
130
+ try {
131
+ message = createUserMessage({ content: [{ type: "text", text }], source: { kind: "user" } });
132
+ } catch (err) {
133
+ ctx.logger.warn(`mobile-remote: /send 消息体构造失败:${failureDetail(err)}`);
134
+ finalize(res, 500, { error: "send-failed", detail: failureDetail(err) });
135
+ return;
136
+ }
137
+
138
+ try {
139
+ if (steer && target.status !== "idle" && typeof target.steer === "function") {
140
+ if (hasImages) {
141
+ await prompt("steer");
142
+
143
+
144
+ finalize(res, 200, { ok: true, accepted: true, agentId: target.id, mode: "steer", note: "image-prompt" });
145
+ } else {
146
+ target.steer(message);
147
+ finalize(res, 200, { ok: true, agentId: target.id, messageId: message.id, mode: "steer" });
148
+ }
149
+ } else if (target.status === "running") {
150
+
151
+ const heldEntry = hasImages
152
+ ? { id: message.id, text, images, at: Date.now() }
153
+ : { id: message.id, text, at: Date.now() };
154
+ heldQueue.set(target.id, [...heldOf(target.id), heldEntry]);
155
+ persistHeld();
156
+ broadcastQueue(target.id);
157
+ finalize(res, 200, {
158
+ ok: true,
159
+
160
+ ...(hasImages ? { accepted: true } : {}),
161
+ agentId: target.id,
162
+ messageId: message.id,
163
+ mode: "queued",
164
+ note: steer ? "steer-degraded-held" : "held-until-idle",
165
+ });
166
+ } else {
167
+ if (steer && target.status === "idle") {
168
+
169
+ if (hasImages) {
170
+ await prompt("queue");
171
+ finalize(res, 200, { ok: true, accepted: true, agentId: target.id, mode: "followup", note: "image-prompt" });
172
+ } else {
173
+ target.followup(message);
174
+ finalize(res, 200, { ok: true, agentId: target.id, messageId: message.id, mode: "followup", note: "agent-idle-followup" });
175
+ }
176
+ return;
177
+ }
178
+ if (hasImages) {
179
+ await prompt("queue");
180
+ finalize(res, 200, { ok: true, accepted: true, agentId: target.id, mode: "followup", note: "image-prompt" });
181
+ } else {
182
+ target.followup(message);
183
+ finalize(res, 200, { ok: true, agentId: target.id, messageId: message.id, mode: "followup" });
184
+ }
185
+ }
186
+ } catch (err) {
187
+ ctx.logger.warn(`mobile-remote: send 失败:${err?.message ?? err}`);
188
+
189
+ const failure = { error: "send-failed", detail: failureDetail(err) };
190
+ return finalize(res, 500, failure);
191
+ }
192
+ return;
193
+ }
194
+
195
+
196
+ if (rest === "/send-receipt") {
197
+ if (requireGet(method, res)) return;
198
+ const sessionId = url.searchParams.get("sessionId") ?? undefined;
199
+ const requestId = url.searchParams.get("requestId");
200
+ if (!requestId || !/^[A-Za-z0-9-]{8,64}$/.test(requestId)) return error(res, 400, "bad-request", "invalid requestId");
201
+ const rootId = firstRootAgent(ctx.get("agents"))?.id;
202
+ const key = receiptKeyOf(sessionId, rootId, requestId);
203
+
204
+ if (pruneReceipts()) persistReceipts();
205
+ let entry = sendReceipts.get(key);
206
+ if (entry && receiptExpired(entry.at, Date.now(), RECEIPT_TTL)) {
207
+
208
+ sendReceipts.delete(key);
209
+ persistReceipts();
210
+ entry = undefined;
211
+ }
212
+ if (!entry) return error(res, 404, "receipt-not-found", "该回执不存在或已过期");
213
+ if (entry.status === "in-progress") return sendJson(res, 200, { ok: true, receipt: { status: "in-progress", result: null } });
214
+ return sendJson(res, 200, { ok: true, receipt: { status: entry.status, result: entry.result ?? null } });
215
+ }
216
+
217
+
218
+ if (rest === "/attachment") {
219
+ if (requireGet(method, res)) return;
220
+ const sessionId = url.searchParams.get("sessionId");
221
+ const attachmentId = url.searchParams.get("attachmentId");
222
+ if (!sessionId || !attachmentId) return error(res, 400, "bad-request", "sessionId/attachmentId required");
223
+ try {
224
+ const value = await apiRpc("session.attachment", { sessionId, attachmentId }, 30_000);
225
+ const ref = value?.attachment;
226
+ if (!ref || typeof value?.data !== "string" || value.data === "") return error(res, 404, "attachment-not-found");
227
+ const buf = Buffer.from(value.data, "base64");
228
+ guardRes(res);
229
+ res.writeHead(200, {
230
+ "content-type": typeof ref.mediaType === "string" ? ref.mediaType : "image/jpeg",
231
+ "content-length": buf.length,
232
+ "cache-control": "private, max-age=3600",
233
+
234
+ "connection": "close",
235
+ "x-attachment-meta": JSON.stringify({
236
+ width: Number.isFinite(ref.width) ? ref.width : 0,
237
+ height: Number.isFinite(ref.height) ? ref.height : 0,
238
+ bytes: Number.isFinite(ref.bytes) ? ref.bytes : buf.length,
239
+ name: typeof ref.name === "string" ? ref.name : null,
240
+ }),
241
+ });
242
+ res.end(buf);
243
+ } catch (err) {
244
+ return error(res, ...rpcError(err, "attachment-failed"));
245
+ }
246
+ return;
247
+ }
248
+
249
+
250
+
251
+ if (rest === "/queue") {
252
+ if (requireGet(method, res)) return;
253
+ const sessionId = url.searchParams.get("sessionId");
254
+ if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
255
+ const sessions = ctx.get("sessions");
256
+ const agents = ctx.get("agents");
257
+ const agent = agents ? agents.get(sessionId) : undefined;
258
+ if (!agent && !sessions?.get(sessionId)) return error(res, 404, "session-not-found");
259
+
260
+ sendJson(res, 200, { ok: true, queue: queueRowsOf(sessionId) });
261
+ return;
262
+ }
263
+
264
+
265
+
266
+ if (rest === "/messages") {
267
+ if (requirePost(method, res)) return;
268
+ const body = await readJson(req, res);
269
+ if (body === undefined) return;
270
+ const sessionId = typeof body?.sessionId === "string" ? body.sessionId : "";
271
+ const itemId = typeof body?.itemId === "string" ? body.itemId : "";
272
+ const action = body?.action;
273
+ if (!sessionId || !itemId) return error(res, 400, "bad-request", "sessionId/itemId required");
274
+ if (!action || !["edit", "remove", "steer"].includes(action.kind)) {
275
+ return error(res, 400, "bad-request", "action.kind must be edit | remove | steer");
276
+ }
277
+ if (action.kind === "edit") {
278
+
279
+ if (!Array.isArray(action.content) || action.content.length === 0) {
280
+ return error(res, 400, "bad-request", "edit requires non-empty content");
281
+ }
282
+ if (!action.content.some((b) => b?.type === "text" && typeof b.text === "string")) {
283
+ return error(res, 400, "bad-request", "edit requires at least one text block");
284
+ }
285
+ }
286
+
287
+ const held = [...heldOf(sessionId)];
288
+ const heldIdx = held.findIndex((m) => m.id === itemId);
289
+ if (heldIdx !== -1) {
290
+ const agents = ctx.get("agents");
291
+ const agent = agents?.get(sessionId);
292
+ try {
293
+ if (action.kind === "edit") {
294
+ const newText = action.content.filter((b) => b?.type === "text").map((b) => b.text).join("");
295
+ held[heldIdx] = { ...held[heldIdx], text: newText, at: Date.now() };
296
+ } else if (action.kind === "remove") {
297
+ held.splice(heldIdx, 1);
298
+ } else {
299
+
300
+
301
+
302
+
303
+
304
+ if (!agent) {
305
+ return error(res, 409, "steer-unavailable", "会话当前不在内存中,无法插队(消息仍在排队,稍后会自动释放)");
306
+ }
307
+ const item = held.splice(heldIdx, 1)[0];
308
+ if (item.images?.length) {
309
+
310
+ const running = agent.status !== "idle" && typeof agent.steer === "function";
311
+ await promptImage(sessionId, running ? "steer" : "queue", heldContentOf(item));
312
+ } else {
313
+ const message = createUserMessage({ content: [{ type: "text", text: item.text }], source: { kind: "user" } });
314
+ if (agent.status !== "idle" && typeof agent.steer === "function") {
315
+ agent.steer(message);
316
+ } else {
317
+ agent.followup(message);
318
+ }
319
+ }
320
+ }
321
+ heldQueue.set(sessionId, held);
322
+ persistHeld();
323
+ broadcastQueue(sessionId);
324
+ sendJson(res, 200, { ok: true, accepted: true });
325
+ } catch (err) {
326
+ return error(res, 500, "queue-hold-failed", failureDetail(err));
327
+ }
328
+ return;
329
+ }
330
+ try {
331
+ const value = await apiRpc("session.updateQueue", { sessionId, itemId, action });
332
+ sendJson(res, 200, { ok: true, ...(value ?? {}) });
333
+ } catch (err) {
334
+ ctx.logger.warn(`mobile-remote: updateQueue failed: ${err?.message ?? err}`);
335
+ return error(res, ...rpcError(err, "update-queue-failed"));
336
+ }
337
+ return;
338
+ }
339
+ miss.now = true;
340
+ return NOT_HANDLED;
341
+ }