@dsh-mobile/mobile-remote 3.2.4 → 3.2.5

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 (57) hide show
  1. package/CHANGELOG.md +204 -0
  2. package/FAQ.md +4 -0
  3. package/README.md +21 -14
  4. package/docs/01-PRD.md +4 -4
  5. package/docs/02-architecture.md +1 -1
  6. package/docs/03-api.md +49 -1
  7. package/docs/05-test-cases.md +7 -7
  8. package/docs/06-install-run.md +16 -3
  9. package/docs/07-user-manual.md +23 -1
  10. package/docs/08-/346/211/251/345/261/225/345/274/200/345/217/221/346/214/207/345/215/227.md +2 -2
  11. package/docs/09-compatibility.md +3 -3
  12. package/docs/10-remote-access-and-launch-plan.md +216 -0
  13. package/docs/11-remote-relay-guide.md +82 -0
  14. package/docs/APP-ENCRYPTION-DESCRIPTION.md +50 -0
  15. package/docs/APP-ENCRYPTION-DESCRIPTION.pdf +0 -0
  16. package/docs/AUDIT-2026-11-node.md +181 -0
  17. package/docs/AUDIT-2026-11.md +167 -0
  18. package/docs/BRAND-ASSETS.md +142 -0
  19. package/docs/BUILD-ENVIRONMENT.md +15 -4
  20. package/docs/FEATURE-PARITY.md +2 -2
  21. package/docs/PRIVACY-POLICY.en.md +143 -0
  22. package/docs/PRIVACY-POLICY.md +108 -30
  23. package/docs/STORE-LAUNCH.md +169 -21
  24. package/docs/STORE-LISTING.md +150 -0
  25. package/docs/SUPPORT.md +4 -3
  26. package/docs/TERMS-OF-SERVICE.en.md +70 -0
  27. package/docs/TERMS-OF-SERVICE.md +70 -0
  28. package/docs/screenshots/01-home.png +0 -0
  29. package/docs/screenshots/02-notifications.png +0 -0
  30. package/docs/screenshots/03-sessions.png +0 -0
  31. package/docs/screenshots/04-chat.png +0 -0
  32. package/docs/screenshots/05-settings.png +0 -0
  33. package/docs/screenshots/06-new-session.png +0 -0
  34. package/docs/screenshots/07-connect.png +0 -0
  35. package/lib/account-usage-query.js +278 -0
  36. package/lib/api-helpers.js +333 -0
  37. package/lib/client.js +284 -1
  38. package/lib/config.js +211 -0
  39. package/lib/host-compat.js +133 -0
  40. package/lib/http-util.js +69 -0
  41. package/lib/index.js +179 -2009
  42. package/lib/push.js +73 -0
  43. package/lib/rate-limit.js +46 -0
  44. package/lib/relay/connector.js +300 -0
  45. package/lib/relay/crypto.js +117 -0
  46. package/lib/relay/devices.js +138 -0
  47. package/lib/relay/identity.js +60 -0
  48. package/lib/relay/mux.js +411 -0
  49. package/lib/relay/noise.js +178 -0
  50. package/lib/relay/pairing.js +64 -0
  51. package/lib/relay/phone.js +114 -0
  52. package/lib/relay/serve.js +105 -0
  53. package/lib/rpc-adapter.js +88 -0
  54. package/lib/session-list.js +77 -0
  55. package/lib/timeline.js +476 -0
  56. package/lib/turn-outline.js +289 -0
  57. package/package.json +1 -1
@@ -0,0 +1,64 @@
1
+ /**
2
+ * 配对链接:二维码里编码的内容。
3
+ *
4
+ * dsh://pair?v=1&room=<32 位十六进制>&pk=<电脑 X25519 公钥 base64url>&otp=<一次性配对码>
5
+ * &r=<中继 wss 地址>(可多个)&lan=<局域网地址>(可多个,可选)&n=<电脑名称>(可选)
6
+ *
7
+ * 手机只需要这些:去哪个中继、哪个房间、认哪把公钥、拿什么码证明「我是被邀请的」。
8
+ * 解析是严格的:中继必须是 wss://(回环地址的 ws:// 仅供本机测试),其它一律拒绝。
9
+ */
10
+ import { b64u } from "./crypto.js";
11
+
12
+ const ROOM_RE = /^[0-9a-f]{32}$/;
13
+ const MAX_URIS = 4;
14
+
15
+ const isLoopbackHost = (h) => h === "localhost" || h === "127.0.0.1" || h === "[::1]" || h === "::1";
16
+
17
+ export function isAllowedRelayUrl(s) {
18
+ try {
19
+ const u = new URL(s);
20
+ if (u.username || u.password || u.search || u.hash) return false;
21
+ if (u.protocol === "wss:") return true;
22
+ return u.protocol === "ws:" && isLoopbackHost(u.hostname);
23
+ } catch {
24
+ return false;
25
+ }
26
+ }
27
+
28
+ export function buildPairingUri({ relays, roomId, pcPub, otp, name, lan = [] }) {
29
+ if (!ROOM_RE.test(roomId)) throw new Error("bad room id");
30
+ if (pcPub.length !== 32) throw new Error("bad public key");
31
+ if (!Array.isArray(relays) || relays.length === 0 || relays.length > MAX_URIS) throw new Error("need 1-4 relay urls");
32
+ for (const r of relays) if (!isAllowedRelayUrl(r)) throw new Error(`relay url must be wss:// : ${r}`);
33
+ const q = new URLSearchParams();
34
+ q.set("v", "1");
35
+ q.set("room", roomId);
36
+ q.set("pk", b64u.enc(pcPub));
37
+ q.set("otp", otp);
38
+ for (const r of relays) q.append("r", r.replace(/\/+$/, ""));
39
+ for (const l of lan.slice(0, MAX_URIS)) q.append("lan", l);
40
+ if (name) q.set("n", String(name).slice(0, 40));
41
+ return `dsh://pair?${q.toString()}`;
42
+ }
43
+
44
+ export function parsePairingUri(uri) {
45
+ let u;
46
+ try {
47
+ u = new URL(uri);
48
+ } catch {
49
+ throw new Error("not a url");
50
+ }
51
+ if (u.protocol !== "dsh:" || u.hostname !== "pair") throw new Error("not a DSH pairing link");
52
+ const p = u.searchParams;
53
+ if (p.get("v") !== "1") throw new Error("unsupported version");
54
+ const room = p.get("room") ?? "";
55
+ if (!ROOM_RE.test(room)) throw new Error("bad room id");
56
+ const pk = b64u.dec(p.get("pk") ?? "");
57
+ if (pk.length !== 32) throw new Error("bad public key");
58
+ const otp = p.get("otp") ?? "";
59
+ if (otp.length < 16 || otp.length > 64 || !/^[A-Za-z0-9_-]+$/.test(otp)) throw new Error("bad pairing code");
60
+ const relays = p.getAll("r").map((r) => r.replace(/\/+$/, ""));
61
+ if (relays.length === 0 || relays.length > MAX_URIS) throw new Error("need 1-4 relay urls");
62
+ for (const r of relays) if (!isAllowedRelayUrl(r)) throw new Error("relay url must be wss://");
63
+ return { room, pk, otp, relays, lan: p.getAll("lan").slice(0, MAX_URIS), name: p.get("n") ?? "" };
64
+ }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * 手机端协议的参考实现(Node)。
3
+ *
4
+ * 用途:①测试里扮演手机,端到端验证中继 / 连接器 / 插件;②给 Flutter 端当「可执行的规格」——
5
+ * Dart 实现必须与它逐字节互通(见 test/vectors/ 里的确定性转录)。
6
+ *
7
+ * 流程:连中继(访客身份)→ 等房主在线 → Noise 发起方握手(消息 1 里带上设备名与一次性配对码)→
8
+ * 读消息 2 → 之后所有流量都是 Noise 传输消息,里面跑多路复用的 HTTP。
9
+ */
10
+ import { MuxSession } from "./mux.js";
11
+ import { NoiseInitiator } from "./noise.js";
12
+
13
+ const enc = new TextEncoder();
14
+ const dec = new TextDecoder();
15
+
16
+ export class PhoneSession {
17
+ constructor() {
18
+ this.info = null;
19
+ this.closeCode = null;
20
+ this.closeReason = "";
21
+ this.closed = new Promise((resolve) => (this._resolveClosed = resolve));
22
+ }
23
+ request(req) {
24
+ return this.mux.request(req);
25
+ }
26
+ close(code = 1000, reason = "bye") {
27
+ this._shutdown(code, reason);
28
+ try {
29
+ this.ws.close(code, reason);
30
+ } catch {
31
+ /* 已断开 */
32
+ }
33
+ }
34
+ _shutdown(code, reason) {
35
+ if (this.closeCode !== null) return;
36
+ this.closeCode = code;
37
+ this.closeReason = reason;
38
+ clearInterval(this.pinger);
39
+ this.mux?.close(`closed ${code}`);
40
+ this._resolveClosed({ code, reason });
41
+ }
42
+ }
43
+
44
+ /**
45
+ * @param {{ relayUrl:string, room:string, pcPub:Uint8Array, device:{priv:Uint8Array,pub:Uint8Array},
46
+ * name?:string, otp?:string, WebSocketImpl?:Function, timeoutMs?:number }} o
47
+ */
48
+ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", otp, WebSocketImpl = globalThis.WebSocket, timeoutMs = 10_000 }) {
49
+ return new Promise((resolve, reject) => {
50
+ const phone = new PhoneSession();
51
+ const ws = new WebSocketImpl(`${relayUrl.replace(/\/+$/, "")}/v1/guest/${room}`);
52
+ ws.binaryType = "arraybuffer";
53
+ phone.ws = ws;
54
+ const noise = new NoiseInitiator({ s: device, rs: pcPub, prologue: enc.encode(`DSH-RELAY/1|${room}`) });
55
+ let stage = "relay"; // relay → handshake → open
56
+ let cipherOut = null;
57
+ let cipherIn = null;
58
+ const fail = (err) => {
59
+ clearTimeout(timer);
60
+ phone._shutdown(phone.closeCode ?? 4000, String(err?.message ?? err));
61
+ try {
62
+ ws.close();
63
+ } catch {
64
+ /* 已断开 */
65
+ }
66
+ reject(err instanceof Error ? err : new Error(String(err)));
67
+ };
68
+ const timer = setTimeout(() => fail(new Error(`connect timeout in stage ${stage}`)), timeoutMs);
69
+
70
+ const startHandshake = () => {
71
+ stage = "handshake";
72
+ ws.send(noise.writeMessage1(enc.encode(JSON.stringify({ v: 1, name, ...(otp ? { otp } : {}) }))));
73
+ };
74
+ ws.addEventListener("message", (e) => {
75
+ try {
76
+ if (typeof e.data === "string") {
77
+ const msg = JSON.parse(e.data);
78
+ if (stage === "relay" && msg.t === "hello" && msg.host === true) return startHandshake();
79
+ if (msg.t === "host-up") {
80
+ if (stage === "relay") return startHandshake();
81
+ // 电脑重新上线(重启 / 换连接):我们的 Noise 会话已经无处可去,上层应重新连接
82
+ return phone._shutdown(4503, "host restarted");
83
+ }
84
+ return;
85
+ }
86
+ const bytes = new Uint8Array(e.data);
87
+ if (stage === "handshake") {
88
+ const done = noise.readMessage2(bytes);
89
+ cipherOut = done.send;
90
+ cipherIn = done.recv;
91
+ phone.info = JSON.parse(dec.decode(done.payload));
92
+ phone.mux = new MuxSession({ role: "client", send: (frame) => ws.send(cipherOut.encrypt(frame)) });
93
+ phone.pinger = setInterval(() => { try { ws.send(JSON.stringify({ t: "ping" })); } catch { /* 连接正在断开 */ } }, 20_000);
94
+ phone.pinger.unref?.();
95
+ stage = "open";
96
+ clearTimeout(timer);
97
+ return resolve(phone);
98
+ }
99
+ if (stage === "open") phone.mux.receive(cipherIn.decrypt(bytes));
100
+ } catch (err) {
101
+ if (stage !== "open") return fail(err);
102
+ phone.close(4000, "protocol error");
103
+ }
104
+ });
105
+ ws.addEventListener("close", (e) => {
106
+ phone._shutdown(e.code ?? 1006, e.reason ?? "");
107
+ if (stage !== "open") {
108
+ clearTimeout(timer);
109
+ reject(Object.assign(new Error(`relay closed during ${stage} (${e.code})`), { code: e.code }));
110
+ }
111
+ });
112
+ ws.addEventListener("error", () => {});
113
+ });
114
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * 把隧道里来的请求「回放」给插件自己的 HTTP 服务(回环),再把响应流式送回去。
3
+ *
4
+ * 这是整个中继方案里最敏感的一步:回放的请求从 127.0.0.1 发出,和「电脑桌面 GUI」的请求长得一样。
5
+ * 如果不加防护,一台已配对的手机就能拿到只给桌面看的端点(比如 /qr-config 会返回局域网口令)。三层防护:
6
+ *
7
+ * ① 路径白名单:只放行 `${basePath}/api/…`,并明确拒绝 qr-config / qr.png / relay 管理 / dev 端点;
8
+ * 任何会被 URL 规范化改变的路径(`..`、`//`、`%2f`、反斜杠)直接拒绝,防止绕过白名单;
9
+ * ② 清洗请求头:丢掉手机自带的口令 / cookie / 代理头 / 浏览器来源头;然后写入我们自己的头——
10
+ * 有效来源 IP = `relay:<设备>`(不是回环,桌面闸门因此判为非本机)、`via`(桌面闸门看到代理头即拒)、
11
+ * 以及只存在于本进程内存的随机令牌(证明「这个请求确实是连接器发的」,插件据此免口令放行);
12
+ * ③ 插件自己的闸门(localDesktopGate)仍然独立生效,前两层任何一层出错它都兜底。
13
+ */
14
+ import http from "node:http";
15
+ import { Readable } from "node:stream";
16
+
17
+ const METHODS = new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]);
18
+ const DROP_REQUEST = new Set([
19
+ "host", "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade",
20
+ "content-length", "accept-encoding", "x-mobile-token", "cookie", "forwarded", "x-forwarded-for", "x-forwarded-host", "x-forwarded-proto",
21
+ "x-forwarded-port", "x-real-ip", "via", "origin", "referer", "sec-fetch-site", "sec-fetch-mode", "sec-fetch-dest", "sec-fetch-user",
22
+ "x-dsh-relay-peer", "x-dsh-mobile-client-ip",
23
+ ]);
24
+ const DROP_RESPONSE = new Set(["connection", "keep-alive", "transfer-encoding", "set-cookie", "proxy-authenticate", "upgrade"]);
25
+ const DENIED = [/^\/api\/qr-config(\/|$)/, /^\/api\/qr\.png(\/|$)/, /^\/api\/relay(\/|$)/, /^\/api\/dev(\/|$)/];
26
+
27
+ /** 返回 null 表示放行;否则返回拒绝原因。导出以便直接测试。 */
28
+ export function checkPath(rawPath, basePath) {
29
+ if (typeof rawPath !== "string" || rawPath === "" || rawPath.length > 4096) return "bad-path";
30
+ if (/[\\\u0000-\u001f\u007f]/.test(rawPath)) return "bad-path";
31
+ const q = rawPath.indexOf("?");
32
+ const pathname = q < 0 ? rawPath : rawPath.slice(0, q);
33
+ if (/%(2f|5c|2e|00)/i.test(pathname)) return "bad-path"; // 编码的 / \ . NUL 不会出现在合法路由里
34
+ let normalized;
35
+ try {
36
+ normalized = new URL(rawPath, "http://relay.invalid").pathname;
37
+ } catch {
38
+ return "bad-path";
39
+ }
40
+ if (normalized !== pathname) return "bad-path"; // 规范化改变了路径(.. 或 //)= 试图绕过
41
+ if (!pathname.startsWith(`${basePath}/api/`)) return "path-not-allowed";
42
+ const rest = pathname.slice(basePath.length);
43
+ if (DENIED.some((re) => re.test(rest))) return "path-not-allowed";
44
+ return null;
45
+ }
46
+
47
+ /** `check` 仅供测试:换成「全部放行」来验证第二、三层防护在白名单失守时仍然成立。生产不传。 */
48
+ export function createHttpReplayer({ port, basePath, relayToken, ipToken, peerHeader, ipHeader, maxBodyBytes = 64 * 1024 * 1024, check = checkPath }) {
49
+ return async function serve(stream, device) {
50
+ let responded = false;
51
+ const reply = (status, code) => {
52
+ if (responded) return stream.reset(5);
53
+ responded = true;
54
+ stream.respond(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
55
+ stream.write(JSON.stringify({ ok: false, error: code }));
56
+ stream.end();
57
+ };
58
+ if (!METHODS.has(stream.method)) return reply(405, "method-not-allowed");
59
+ const bad = check(stream.path, basePath);
60
+ if (bad) return reply(bad === "bad-path" ? 400 : 403, bad);
61
+
62
+ const headers = {};
63
+ for (const [k, v] of Object.entries(stream.headers)) if (!DROP_REQUEST.has(k)) headers[k] = v;
64
+ headers.host = `127.0.0.1:${port()}`;
65
+ headers[peerHeader] = `${relayToken}|${device.id}`;
66
+ headers[ipHeader] = `${ipToken}|relay:${device.id}`;
67
+ headers.via = "1.1 dsh-relay";
68
+ headers["accept-encoding"] = "identity"; // 隧道里不需要再压缩;SSE 更不能被压缩缓冲
69
+
70
+ const upstream = http.request({ host: "127.0.0.1", port: port(), method: stream.method, path: stream.path, headers, agent: false });
71
+ stream.signal.addEventListener("abort", () => upstream.destroy(), { once: true });
72
+
73
+ let received = 0;
74
+ const body = Readable.fromWeb(stream.body);
75
+ body.on("data", (chunk) => {
76
+ received += chunk.length;
77
+ if (received > maxBodyBytes) {
78
+ upstream.destroy();
79
+ body.destroy();
80
+ reply(413, "body-too-large");
81
+ }
82
+ });
83
+ body.on("error", () => upstream.destroy());
84
+ body.pipe(upstream);
85
+
86
+ upstream.on("response", async (up) => {
87
+ try {
88
+ if (responded) return up.destroy();
89
+ responded = true;
90
+ const out = {};
91
+ for (const [k, v] of Object.entries(up.headers)) if (!DROP_RESPONSE.has(k) && v !== undefined) out[k] = Array.isArray(v) ? v.join(", ") : v;
92
+ stream.respond(up.statusCode ?? 502, out);
93
+ for await (const chunk of up) await stream.write(chunk); // 受流控:手机读得慢,这里就慢
94
+ stream.end();
95
+ } catch {
96
+ up.destroy(); // 手机取消了(SSE 关闭)或隧道断了:别再拉上游
97
+ stream.reset(5); // 上游也可能截断响应;必须让手机读流失败,不能一直等 END
98
+ }
99
+ });
100
+ upstream.on("error", () => {
101
+ if (!responded) reply(502, "upstream-unavailable");
102
+ else stream.reset(5);
103
+ });
104
+ };
105
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * 手机 API → 内核 RPC 的端点改名 / 载荷适配表,以及 RPC 失败到 HTTP 错误三元组的统一映射。
3
+ * 从 lib/index.js 原样拆出(行为不变)。
4
+ */
5
+ import { randomUUID } from "node:crypto";
6
+ import { redactPathText } from "./api-helpers.js";
7
+
8
+ // v3.1.2(适配 DSH 0.1.2-rc.1)——内核 RPC 契约变化:
9
+ // ① 端点命名 namespace.method → namespace/method(session.models → session/modelCatalog、
10
+ // session.history → session/control、goal.create → goals/create、subagent.* → subagents.*);
11
+ // ② 载荷按新参数形态适配(单 request 包装 / 多参数平铺 / 零参数,见网关 typert 定义);
12
+ // ③ 桌面 2.0.5 起 /api HTTP 通道被浏览器访问门禁+会话 Cookie 鉴权关闭(插件 fetch 必 403),
13
+ // 统一改走进程内 ctx.typertGateway.invokeRpc(@Remote 网关,与宿主同域直通服务层)。
14
+ // 旧宿主(无网关 / 接口未迁移)保留原 HTTP /api 降级路径(载荷保持旧契约不适配)。
15
+ // v3.1.5(PR #11 P0):goal/subagent 的命名空间在内核注册表里是**复数**且参数是命名 wire 字段。
16
+ // 网关按 `<namespace>/<method>` 严格查表并在 assertExactArguments 里逐字段比对
17
+ // (@deepseek-ai/dsh-api-gateway/lib/index.js:738-762、1040-1051:endpoint 缺失报
18
+ // gateway/invocation-unavailable、字段不符报 gateway/arguments-invalid),
19
+ // 旧值 "subagent/list"、"subagent/interrupt"(单数命名空间 + 错方法名)与 goal/* 必然失败 →
20
+ // 手机「子代理」「目标」面板恒报错。注册表事实(dsh-api-remotes/lib/client.js):
21
+ // subagents/list(parentSessionId)、subagents/interruptByParent(childSessionId,parentSessionId,mode)、
22
+ // goals/create(agentId,request{objective,maxGoalRounds?})、goals/{pause,resume,complete}(agentId,ref{id,revision})。
23
+ // mode 在内核里是 z.literal("continuable"),故缺省即该唯一合法值。
24
+ const goalRefArgs = (p) => ({ agentId: p.sessionId, ref: p.ref });
25
+ export const RPC_ENDPOINT_RENAMES = {
26
+ "session.models": "session/modelCatalog",
27
+ "session.history": "session/control",
28
+ "subagent.list": "subagents/list",
29
+ "subagent.interrupt": "subagents/interruptByParent",
30
+ "goal.create": "goals/create",
31
+ "goal.pause": "goals/pause",
32
+ "goal.resume": "goals/resume",
33
+ "goal.complete": "goals/complete",
34
+ };
35
+ export const RPC_PAYLOAD_ADAPTER = {
36
+ "session.prompt": (p) => ({ request: { requestId: randomUUID(), sessionId: p.sessionId, mode: p.mode, content: p.content } }),
37
+ "session.attachment": (p) => ({ request: p }),
38
+ "session.updateQueue": (p) => ({ request: p }),
39
+ "session.selectModel": (p) => ({ request: p }),
40
+ "session.cancel": (p) => ({ request: p }),
41
+ "session.fork": (p) => ({ request: p }),
42
+ "session.models": () => ({}),
43
+ "session.history": () => ({}),
44
+ "session.control": () => ({}),
45
+ "workspace.archiveSession": (p) => ({ request: p }),
46
+ "settings.update": (p) => ({ ns: p.ns, patch: p.patch, ...(p.expectedRevision === undefined ? {} : { expectedRevision: p.expectedRevision }) }),
47
+ "subagent.list": (p) => ({ parentSessionId: p.parentSessionId }),
48
+ "subagent.interrupt": (p) => ({ childSessionId: p.childSessionId, parentSessionId: p.parentSessionId, mode: p.mode ?? "continuable" }),
49
+ "goal.create": (p) => ({ agentId: p.sessionId, request: { objective: p.objective, ...(p.maxGoalRounds === undefined ? {} : { maxGoalRounds: p.maxGoalRounds }) } }),
50
+ "goal.pause": goalRefArgs,
51
+ "goal.resume": goalRefArgs,
52
+ "goal.complete": goalRefArgs,
53
+ };
54
+ // 流式端点:只取首帧(如 session/control 基线流),unary invoke 会被网关拒绝
55
+ export const RPC_STREAM_METHODS = new Set(["session.control"]);
56
+ /** v3.1.2:session/control(baseline)中取某会话的投影值(modelSelection/imageLimits 等)。 */
57
+ export const projectionOf = (control, sessionId) =>
58
+ control?.type === "baseline" ? control.value?.projections?.[sessionId]?.values : undefined;
59
+
60
+ // Phase 1(S3):apiRpc 失败统一映射——传输层 502、超时/中止 504、内核错误透传 status(默认 400),
61
+ // 错误码兜底 fallbackCode。返回 [status, code, message] 元组,展开进 error():
62
+ // error(res, ...rpcError(err, "xxx-failed")) → { error: code, detail: message }
63
+ // v2.8.2 修复:调用展开 f(...obj) 走迭代器协议,要求 obj 为 iterable——普通对象字面量与
64
+ // Object.create(null) 均非 iterable,会抛 "Spread syntax requires ...iterable[Symbol.iterator]":
65
+ // 2.8.1 起全部 11 处 API 错误路径因此退化为 HTTP 500 { error: "internal" },真实 status/code/detail
66
+ // 全部丢失(该 TypeError 上抛到 handleApi 外层 catch)。数组是唯一同时满足展开与三元组表达的形态。
67
+ // code 仅接受非空 string:内核自定义错误码是文档字符串(queue-item-not-found 等),
68
+ // DOMException.code 等数字码不在契约内 → 落 fallbackCode(行为收窄,见 docs 契约)。
69
+ export const rpcError = (err, fallbackCode) => {
70
+ const rawCode = typeof err?.code === "string" && err.code !== "" ? err.code : fallbackCode;
71
+ const code = rawCode === "session/not-found" ? "session-not-found" : rawCode;
72
+ const status = code === "session-not-found"
73
+ ? 404
74
+ : err?.status === 502
75
+ ? 502
76
+ : err?.name === "TimeoutError" || err?.name === "AbortError"
77
+ ? 504
78
+ : err?.status ?? 400;
79
+ // v3.1.5 S7:内核错误原文只进日志;回客户端的 detail 一律脱敏(宿主 message 常带
80
+ // 会话/工作区/设置文件绝对路径)。这里覆盖全部 rpcError 调用点。
81
+ let message;
82
+ try {
83
+ message = redactPathText(err?.message ?? String(err));
84
+ } catch {
85
+ message = String(fallbackCode);
86
+ }
87
+ return [status, code, message];
88
+ };
@@ -0,0 +1,77 @@
1
+ /**
2
+ * 会话列表排序键与「消息时间表」剪枝计划(纯函数)。
3
+ * 从 lib/index.js 原样拆出(行为不变)。
4
+ */
5
+ import { isVisibleConversationMessage } from "./timeline.js";
6
+
7
+ /**
8
+ * 会话列表排序键(ADR 0013):`lastMessageAt` → `lastActivity` → `createdAt`。
9
+ * 后两级只为旧内核/旧插件降级保留,新版正常路径恒有 `lastMessageAt`。
10
+ */
11
+ export const sessionListSortKey = (row) => {
12
+ if (typeof row?.lastMessageAt === "number") return row.lastMessageAt;
13
+ if (typeof row?.lastActivity === "number") return row.lastActivity;
14
+ return typeof row?.createdAt === "number" ? row.createdAt : 0;
15
+ };
16
+
17
+ /** 会话列表排序:时间倒序;**等值时以 id 为次级键**,保证顺序稳定不抖动(US29)。 */
18
+ export const compareSessionsForList = (a, b) => {
19
+ const diff = sessionListSortKey(b) - sessionListSortKey(a);
20
+ if (diff !== 0) return diff;
21
+ return String(a?.id ?? "").localeCompare(String(b?.id ?? ""));
22
+ };
23
+
24
+ /** 取会话日志里最新一条**可见对话消息**的时间(回填用);无消息返回 null。 */
25
+ export const latestMessageTimeOf = (events) => {
26
+ let latest = null;
27
+ for (const event of events ?? []) {
28
+ if (!isVisibleConversationMessage(event)) continue;
29
+ const time = typeof event.time === "number" && Number.isFinite(event.time) ? event.time : null;
30
+ if (time === null) continue;
31
+ if (latest === null || time > latest) latest = time;
32
+ }
33
+ return latest;
34
+ };
35
+
36
+ /** 完整语料观测的新鲜度上限:超过它说明最近没人拉过列表,语料可能落后于新建会话。 */
37
+ export const CORPUS_FRESH_MS = 30 * 60 * 1000;
38
+
39
+ /**
40
+ * 规划 `messageTimeMap` 的存在性剪枝(**纯函数**,供契约自检直接断言)。
41
+ *
42
+ * 为什么按存在性、而不按消息时间的新旧:该表的值是「最近一条消息**发生**的时间」,
43
+ * 不是记录的时效。一个 10 天没说话但**依然存在**的会话若被删掉排序键,就会掉回
44
+ * `lastActivity` 排序而莫名上浮,并触发反复回填。所以只在**会话确实消失**时清理。
45
+ *
46
+ * 三条安全约束:
47
+ * 1. 从未观测过完整语料(`corpusObservedAt === 0`)→ 不剪枝(回退分支只有活动会话,
48
+ * 拿它当"全量"会误删休眠会话);
49
+ * 2. 观测过旧(超过 [CORPUS_FRESH_MS])→ 不剪枝,且清空待确认集合(否则陈旧判断会被
50
+ * 当成"第一次确认",下一轮直接误删);
51
+ * 3. 连续两次观测都缺失才删([misses] 是上一次的待删集合),躲开"新建会话尚未落盘"竞态。
52
+ *
53
+ * @returns `{ remove, misses }`:本轮应删除的 id,以及下一轮的待确认集合。
54
+ */
55
+ export const planMessageTimePrune = ({
56
+ messageTimeIds,
57
+ corpusIds,
58
+ corpusObservedAt,
59
+ misses = new Set(),
60
+ now,
61
+ freshMs = CORPUS_FRESH_MS,
62
+ }) => {
63
+ const corpus = corpusIds instanceof Set ? corpusIds : new Set(corpusIds ?? []);
64
+ const fresh = corpusObservedAt > 0 && corpus.size > 0 && now - corpusObservedAt <= freshMs;
65
+ if (!fresh) {
66
+ // 无观测/观测过旧:不剪枝;丢弃待确认集合,避免陈旧判断变成"已确认"
67
+ return { remove: [], misses: new Set() };
68
+ }
69
+ const nextMisses = new Set();
70
+ const remove = [];
71
+ for (const id of messageTimeIds ?? []) {
72
+ if (corpus.has(id)) continue; // 会话仍存在:保留排序键(哪怕是很久以前的)
73
+ if (misses.has(id)) remove.push(id); // 连续两次缺失 → 确认消失
74
+ else nextMisses.add(id); // 第一次缺失 → 待下轮确认
75
+ }
76
+ return { remove, misses: nextMisses };
77
+ };