dsh-mobile-plugin 0.5.52 → 0.5.53

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,167 @@
1
+ // 桌面出站隧道的独立助手 RPC;私钥只在本机 IPC 中传递,响应按请求编号关联。
2
+ 'use strict';
3
+
4
+ const { spawn } = require('node:child_process');
5
+ const { randomUUID } = require('node:crypto');
6
+ const fs = require('node:fs');
7
+ const path = require('node:path');
8
+ const { resolveBinary, platformId, IPC_VERSION } = require('../tailcat/host-process.cjs');
9
+ const MAX_LINE = 64 * 1024;
10
+
11
+ function failure(code) {
12
+ const error = new Error(code);
13
+ error.code = code;
14
+ return error;
15
+ }
16
+
17
+ function resolveRemoteBinary(options = {}) {
18
+ const exists = options.exists || fs.existsSync;
19
+ const override = (options.env || process.env).DSHM_REMOTE_TUNNEL_HELPER;
20
+ if (typeof override === 'string' && override && exists(override)) return override;
21
+ const root = options.root || path.resolve(__dirname, '../../..');
22
+ const packageRoot = options.packageRoot || path.resolve(__dirname, '../..');
23
+ const platform = options.platformId || platformId();
24
+ if (platform) {
25
+ const name = platform === 'win32-x64' ? 'dsh-tailcat-host.exe' : 'dsh-tailcat-host';
26
+ const bundled = path.join(packageRoot, 'native', platform, name);
27
+ if (exists(bundled)) return bundled;
28
+ if (exists(path.join(root, 'tailcat-host', 'runtime-version.json'))) {
29
+ const development = path.join(root, 'build', 'tailcat-runtime', platform, name);
30
+ if (exists(development)) return development;
31
+ }
32
+ }
33
+ return (options.fallback || resolveBinary)();
34
+ }
35
+
36
+ function createRemoteTunnelHelper(options = {}) {
37
+ const binary = (options.resolve || resolveRemoteBinary)();
38
+ const launch = options.spawn || spawn;
39
+ const pending = new Map();
40
+ let child;
41
+ let ready;
42
+ let closed = false;
43
+ let unsupported = false;
44
+ let generation = 0;
45
+
46
+ function rejectPending(code) {
47
+ for (const item of pending.values()) {
48
+ clearTimeout(item.timer);
49
+ item.reject(failure(code));
50
+ }
51
+ pending.clear();
52
+ }
53
+
54
+ function disable(code) {
55
+ unsupported = code === 'remote-helper-unsupported';
56
+ rejectPending(code);
57
+ const proc = child;
58
+ child = undefined;
59
+ ready = undefined;
60
+ proc?.stdin?.end();
61
+ proc?.kill();
62
+ }
63
+
64
+ function handleLine(line) {
65
+ if (Buffer.byteLength(line) > MAX_LINE) return disable('remote-helper-protocol');
66
+ let value;
67
+ try { value = JSON.parse(line); } catch { return; }
68
+ if (!value || typeof value !== 'object') return;
69
+ if (value.event === 'error' && value.code === 'invalid-command') {
70
+ if ([...pending.values()].some(item => item.command === 'remoteCapabilities')) disable('remote-helper-unsupported');
71
+ return;
72
+ }
73
+ if (value.event !== 'remoteResult' || typeof value.requestId !== 'string') return;
74
+ const item = pending.get(value.requestId);
75
+ if (!item) return;
76
+ pending.delete(value.requestId);
77
+ clearTimeout(item.timer);
78
+ if (value.ok === true && value.result && typeof value.result === 'object') item.resolve(value.result);
79
+ else item.reject(failure('remote-helper-request'));
80
+ }
81
+
82
+ function send(command, fields = {}, timeoutMs = options.timeoutMs || 15000) {
83
+ if (!child?.stdin?.writable) return Promise.reject(failure('remote-helper-closed'));
84
+ const requestId = randomUUID();
85
+ return new Promise((resolve, reject) => {
86
+ const timer = setTimeout(() => {
87
+ pending.delete(requestId);
88
+ const code = command === 'remoteCapabilities' ? 'remote-helper-unsupported' : 'remote-helper-timeout';
89
+ reject(failure(code));
90
+ // start 可能稍后才返回,排在它后面的单设备清理会收回句柄,不影响其他电脑。
91
+ if (fields.deviceId && child?.stdin?.writable) {
92
+ child.stdin.write(`${JSON.stringify({ command: 'remoteClose', requestId: randomUUID(), deviceId: fields.deviceId })}\n`);
93
+ } else disable(code);
94
+ }, timeoutMs);
95
+ pending.set(requestId, { command, resolve, reject, timer });
96
+ const text = JSON.stringify({ ...fields, command, requestId });
97
+ if (Buffer.byteLength(text) > MAX_LINE) {
98
+ clearTimeout(timer);
99
+ pending.delete(requestId);
100
+ reject(failure('remote-helper-request'));
101
+ return;
102
+ }
103
+ child.stdin.write(`${text}\n`, error => {
104
+ if (error && pending.has(requestId)) disable('remote-helper-closed');
105
+ });
106
+ });
107
+ }
108
+
109
+ function start() {
110
+ if (closed) return Promise.reject(failure('remote-helper-closed'));
111
+ if (!binary) return Promise.reject(failure('remote-helper-unavailable'));
112
+ if (unsupported) return Promise.reject(failure('remote-helper-unsupported'));
113
+ if (ready) return ready;
114
+ let proc;
115
+ try { proc = launch(binary, [], { stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true }); }
116
+ catch { return Promise.reject(failure('remote-helper-unavailable')); }
117
+ child = proc;
118
+ generation += 1;
119
+ let buffer = '';
120
+ proc.on('error', () => { if (child === proc) disable('remote-helper-unavailable'); });
121
+ proc.stdin.on('error', () => { if (child === proc) disable('remote-helper-closed'); });
122
+ proc.stdout.setEncoding('utf8');
123
+ proc.stdout.on('data', chunk => {
124
+ if (child !== proc) return;
125
+ buffer += chunk;
126
+ for (let at = buffer.indexOf('\n'); at >= 0; at = buffer.indexOf('\n')) {
127
+ const line = buffer.slice(0, at);
128
+ buffer = buffer.slice(at + 1);
129
+ handleLine(line);
130
+ }
131
+ if (Buffer.byteLength(buffer) > MAX_LINE) disable('remote-helper-protocol');
132
+ });
133
+ proc.on('exit', () => { if (child === proc) disable('remote-helper-closed'); });
134
+ proc.stdin.write(`${JSON.stringify({ version: IPC_VERSION, localPort: 19449, name: 'remote-computer-client', state: null, allowedClients: [] })}\n`);
135
+ ready = send('remoteCapabilities', {}, options.capabilityTimeoutMs || 3000).then(result => {
136
+ if (result.version !== 1 || !result.tailcat || !result.p2p) {
137
+ disable('remote-helper-unsupported');
138
+ throw failure('remote-helper-unsupported');
139
+ }
140
+ return result;
141
+ });
142
+ return ready;
143
+ }
144
+
145
+ return {
146
+ status: () => ({ available: Boolean(binary) && !unsupported && !closed, running: Boolean(child), generation }),
147
+ async request(command, fields = {}) { await start(); return send(command, fields); },
148
+ async closeDevice(deviceId) {
149
+ if (child && !closed && !unsupported) await send('remoteClose', { deviceId });
150
+ },
151
+ async close() {
152
+ if (closed) return;
153
+ closed = true;
154
+ rejectPending('remote-helper-closed');
155
+ const proc = child;
156
+ child = undefined;
157
+ if (!proc || proc.exitCode !== null) return;
158
+ await new Promise(resolve => {
159
+ const timer = setTimeout(() => { proc.kill(); resolve(); }, 3000);
160
+ proc.once('exit', () => { clearTimeout(timer); resolve(); });
161
+ proc.stdin.end();
162
+ });
163
+ },
164
+ };
165
+ }
166
+
167
+ module.exports = { createRemoteTunnelHelper, resolveRemoteBinary };
@@ -0,0 +1,190 @@
1
+ // 远程电脑的 Tailcat/P2P 候选:通过已认证控制通道会合,每台绑定独立持有私钥与句柄。
2
+ 'use strict';
3
+
4
+ const { createRemoteTunnelHelper } = require('./tunnel-helper.cjs');
5
+ const TERMINAL_ERRORS = new Set(['REMOTE_REVOKED', 'REMOTE_EXPIRED']);
6
+ const list = value => [...new Set((Array.isArray(value) ? value : []).filter(item => typeof item === 'string' && item.length <= 256))].sort();
7
+ const same = (a, b) => JSON.stringify(list(a)) === JSON.stringify(list(b));
8
+ const idOf = binding => binding.id || binding.instanceId;
9
+
10
+ function localRoute(url, channel) {
11
+ try {
12
+ const parsed = new URL(url);
13
+ if (parsed.protocol !== 'http:' || parsed.hostname !== '127.0.0.1' || !parsed.port || parsed.username || parsed.password
14
+ || parsed.pathname !== '/' || parsed.search || parsed.hash) return null;
15
+ return { url: parsed.origin, channel };
16
+ } catch { return null; }
17
+ }
18
+
19
+ function createRemoteTunnels({ store, transport, helper = createRemoteTunnelHelper() }) {
20
+ const sessions = new Map();
21
+ const jobs = new Map();
22
+ const versions = new Map();
23
+ let closed = false;
24
+ const generation = () => helper.status?.().generation || 0;
25
+
26
+ function serialized(id, action) {
27
+ const previous = jobs.get(id) || Promise.resolve();
28
+ const next = previous.catch(() => {}).then(action);
29
+ jobs.set(id, next);
30
+ void next.finally(() => { if (jobs.get(id) === next) jobs.delete(id); }).catch(() => {});
31
+ return next;
32
+ }
33
+
34
+ async function keysFor(binding) {
35
+ const id = idOf(binding);
36
+ const stored = await store.get(id) || binding;
37
+ const keys = { ...(stored.tunnelKeys || {}) };
38
+ const tailcat = await helper.request('remoteTailcatKey', { deviceId: id, privateKey: keys.tailcatPrivateKey || '' });
39
+ keys.tailcatPrivateKey = tailcat.privateKey;
40
+ if (!keys.p2pPrivateKey || !keys.p2pPublicKey) {
41
+ const pair = await helper.request('remoteP2PKeys', { deviceId: id, p2pPrivateKey: keys.p2pPrivateKey || '' });
42
+ keys.p2pPrivateKey = pair.private;
43
+ keys.p2pPublicKey = pair.public;
44
+ }
45
+ if (!keys.tailcatPrivateKey || !keys.p2pPrivateKey || !keys.p2pPublicKey || !tailcat.publicKey) throw new Error('remote-helper-keys');
46
+ if (JSON.stringify(keys) !== JSON.stringify(stored.tunnelKeys || {})) {
47
+ if (typeof store.update === 'function') await store.update(id, () => ({ tunnelKeys: keys }));
48
+ else await store.put({ ...stored, id, tunnelKeys: keys });
49
+ }
50
+ return { keys, tailcatPublicKey: tailcat.publicKey };
51
+ }
52
+
53
+ async function control(binding, route, payload) {
54
+ const all = (binding.routes || []).filter(candidate => candidate && typeof candidate.url === 'string');
55
+ const choices = route ? [route] : [...all.slice(0, 1), ...all.filter(item => item.channel === 'relay'), ...all.slice(1)]
56
+ .filter((item, index, rows) => rows.findIndex(other => other.url === item.url) === index);
57
+ for (let index = 0; index < choices.length; index += 2) {
58
+ const batch = choices.slice(index, index + 2).map(async candidate => {
59
+ const result = await transport.callRemoteControl(binding, candidate, payload, { timeoutMs: 15000 });
60
+ return { result, route: candidate };
61
+ });
62
+ const results = await Promise.allSettled(batch);
63
+ const terminal = results.find(item => item.status === 'rejected' && TERMINAL_ERRORS.has(item.reason?.code));
64
+ if (terminal) throw terminal.reason;
65
+ const success = results.find(item => item.status === 'fulfilled');
66
+ if (success) return success.value;
67
+ }
68
+ throw new Error('remote-control-unavailable');
69
+ }
70
+
71
+ async function stopDevice(id) {
72
+ sessions.delete(id);
73
+ try { await helper.closeDevice(id); } catch { /* 已退出的助手没有遗留句柄。 */ }
74
+ }
75
+
76
+ async function initialize(binding, route, version) {
77
+ const id = idOf(binding);
78
+ let entry;
79
+ try {
80
+ const { keys, tailcatPublicKey } = await keysFor(binding);
81
+ if (closed || versions.get(id) !== version) return [];
82
+ const payload = { op: 'tunnels', tailcatPublicKey, p2p: { publicKey: keys.p2pPublicKey, candidates: [], localCandidates: [] } };
83
+ const first = await control(binding, route, payload);
84
+ entry = { routes: [], generation: generation(), controlRoute: first.route, publicKey: keys.p2pPublicKey,
85
+ tailcatPublicKey, candidates: [], localCandidates: [] };
86
+ const tailcat = first.result?.tailcat;
87
+ if (tailcat?.address && Number.isInteger(tailcat.port)) {
88
+ try {
89
+ const started = await helper.request('remoteTailcatStart', { deviceId: id, privateKey: keys.tailcatPrivateKey,
90
+ address: tailcat.address, remotePort: tailcat.port });
91
+ const candidate = localRoute(`http://127.0.0.1:${started.port}`, 'tunnel');
92
+ if (candidate) entry.routes.push(candidate);
93
+ } catch { /* P2P 与基础线路仍可独立使用。 */ }
94
+ }
95
+ const peer = first.result?.p2p;
96
+ if (peer?.publicKey && Number.isInteger(peer.port)) {
97
+ try {
98
+ const started = await helper.request('remoteP2PStart', { deviceId: id, p2pPrivateKey: keys.p2pPrivateKey,
99
+ p2pPeerKey: peer.publicKey, p2pPeerPublic: list(peer.candidates), p2pPeerLocal: list(peer.localCandidates), p2pListenPort: peer.port });
100
+ const candidate = localRoute(started.url, 'p2p');
101
+ if (candidate) {
102
+ const local = await helper.request('remoteP2PCandidates', { deviceId: id });
103
+ entry.candidates = list(local.candidates || started.candidates);
104
+ entry.localCandidates = list(local.localCandidates);
105
+ const second = await control(binding, first.route, { op: 'tunnels.refresh', tailcatPublicKey,
106
+ p2p: { publicKey: keys.p2pPublicKey, candidates: entry.candidates, localCandidates: entry.localCandidates } });
107
+ if (second.result?.p2p?.publicKey !== peer.publicKey) throw new Error('remote-p2p-identity-changed');
108
+ // A 更新接收端后会主动打向这块 B socket;保留 B 句柄,让数据面学习 A 的当前地址。
109
+ entry.routes.push(candidate);
110
+ }
111
+ } catch (error) {
112
+ try { await helper.request('remoteP2PStop', { deviceId: id }); } catch { /* 助手退出即清理。 */ }
113
+ if (TERMINAL_ERRORS.has(error?.code)) throw error;
114
+ }
115
+ }
116
+ if (closed || versions.get(id) !== version || entry.generation !== generation()) {
117
+ await stopDevice(id);
118
+ return [];
119
+ }
120
+ sessions.set(id, entry);
121
+ return entry.routes.map(item => ({ ...item }));
122
+ } catch (error) {
123
+ await stopDevice(id);
124
+ if (TERMINAL_ERRORS.has(error?.code)) throw error;
125
+ return [];
126
+ }
127
+ }
128
+
129
+ async function routesFor(binding) {
130
+ const id = idOf(binding);
131
+ return serialized(id, async () => {
132
+ if (closed) return [];
133
+ const current = sessions.get(id);
134
+ if (current && current.generation === generation() && helper.status?.().running !== false) {
135
+ if (current.routes.some(item => item.channel === 'p2p')) {
136
+ try {
137
+ const local = await helper.request('remoteP2PCandidates', { deviceId: id });
138
+ if (!same(local.candidates, current.candidates) || !same(local.localCandidates, current.localCandidates)) {
139
+ const candidates = list(local.candidates);
140
+ const localCandidates = list(local.localCandidates);
141
+ await control(binding, current.controlRoute, { op: 'tunnels.refresh', tailcatPublicKey: current.tailcatPublicKey,
142
+ p2p: { publicKey: current.publicKey, candidates, localCandidates } });
143
+ current.candidates = candidates;
144
+ current.localCandidates = localCandidates;
145
+ }
146
+ } catch (error) {
147
+ if (TERMINAL_ERRORS.has(error?.code)) {
148
+ await stopDevice(id);
149
+ throw error;
150
+ }
151
+ current.routes = current.routes.filter(item => item.channel !== 'p2p');
152
+ try { await helper.request('remoteP2PStop', { deviceId: id }); } catch { /* 已退出。 */ }
153
+ }
154
+ }
155
+ return current.routes.map(item => ({ ...item }));
156
+ }
157
+ await stopDevice(id);
158
+ const version = versions.get(id) || 0;
159
+ versions.set(id, version);
160
+ return initialize(binding, undefined, version);
161
+ });
162
+ }
163
+
164
+ return {
165
+ routesFor,
166
+ refresh(binding, { route } = {}) {
167
+ const id = idOf(binding);
168
+ const version = (versions.get(id) || 0) + 1;
169
+ versions.set(id, version);
170
+ return serialized(id, async () => {
171
+ await stopDevice(id);
172
+ if (closed || versions.get(id) !== version) return [];
173
+ return initialize(binding, route, version);
174
+ });
175
+ },
176
+ close(id) {
177
+ versions.set(id, (versions.get(id) || 0) + 1);
178
+ return serialized(id, () => stopDevice(id));
179
+ },
180
+ async closeAll() {
181
+ closed = true;
182
+ for (const id of new Set([...sessions.keys(), ...jobs.keys()])) versions.set(id, (versions.get(id) || 0) + 1);
183
+ await Promise.all([...jobs.values()].map(job => job.catch(() => {})));
184
+ sessions.clear();
185
+ await helper.close();
186
+ },
187
+ };
188
+ }
189
+
190
+ module.exports = { createRemoteTunnels };
@@ -1,6 +1,8 @@
1
1
  'use strict';
2
+ // 电脑间配对和网页隧道使用独立加密认证,不复用手机的全权凭据。
2
3
 
3
4
  /**
5
+ * 调试操作记录仅在手机复制,不挂载回传路由。
4
6
  * 移动端 API 路由表(`/api/mobile/v1/*`)。
5
7
  *
6
8
  * 它本身没有逻辑,绝大部分是「路径 → 已写好的 handler」的纯映射,只有 status /
@@ -88,7 +90,6 @@ const pluginCatalog = require('../mobile/plugin-catalog.js');
88
90
  const { createRelayControlHandlers } = require('../mobile/relay-control.js');
89
91
  const uploads = require('../mobile/uploads.js');
90
92
  const inboxClean = require('../mobile/inbox-clean.js');
91
- const perfTrace = require('../mobile/perf-trace.js');
92
93
  // 过程播报开关(读 / 写同一条路径,由 req.method 分派)。默认关,见那个文件头。
93
94
  const narration = require('../mobile/narration.js');
94
95
  // 通知按事件类型分级(GET 读 / PUT 整表替换,按设备分桶)。见那个文件头。
@@ -413,7 +414,6 @@ function registerMobileRoutes(deps) {
413
414
  // 密钥时那头静默忽略——这条路由照常回 ok,「推没推成」不是 App 要操心的事。
414
415
  // 判据(要不要收这个令牌)与配对同一把锁:guarded 已核过设备身份。
415
416
  route('/api/mobile/v1/push-token', pushNotifyRoute.createPushTokenHandler({ pushNotify: deps.pushNotify }))
416
- route('/api/mobile/v1/perf-trace', perfTrace.handlePerfTrace)
417
417
  route('/api/mobile/v1/session', sessions.handleSession)
418
418
  route('/api/mobile/v1/session/messages', sessions.handleMessages)
419
419
  // 一步的过程详情:清单只带一行摘要,点开某一步才来这里取参数 / 输出 / diff / 思考全文。
@@ -805,6 +805,11 @@ function registerMobileRoutes(deps) {
805
805
  // (`mode=webapp` 那一档才允许拨回宿主自己的 web 端口)。
806
806
  route('/api/mobile/v1/host-web', deps.hostWeb)
807
807
 
808
+ if (deps.remoteComputers) {
809
+ registerRoute({ kind: 'exact', path: '/api/mobile/v1/remote-computers/pair', handler: deps.remoteComputers.handlePair })
810
+ registerUpgradeRoute({ path: '/api/mobile/v1/remote-computers/tunnel', handler: deps.remoteComputers.handleUpgrade })
811
+ }
812
+
808
813
  // 内置浏览器预览(App 侧「点 localhost 链接在内置浏览器里打开」的宿主端一半)。
809
814
  //
810
815
  // 这是一条 **WebSocket 升级**路由,不是普通 HTTP 路由:手机原生模块按端口在环回监听、
@@ -0,0 +1,202 @@
1
+ 'use strict';
2
+ // 由 App 自动选路规则同步;运行 scripts/sync-route-policy.mjs 更新。
3
+ function createRoutePolicy() {
4
+ const exports = {};
5
+ "use strict";
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.noteRouteLatency = noteRouteLatency;
8
+ exports.noteRouteFailure = noteRouteFailure;
9
+ exports.noteRouteForeign = noteRouteForeign;
10
+ exports.isRouteForeign = isRouteForeign;
11
+ exports.routeLatencyOf = routeLatencyOf;
12
+ exports.routeCostOf = routeCostOf;
13
+ exports.forgetRouteFacts = forgetRouteFacts;
14
+ exports.orderRouteCandidates = orderRouteCandidates;
15
+ const LOSS_PENALTY_MAX = 4;
16
+ const FAILURE_PENALTY_STEP = 1.5;
17
+ const FAILURE_PENALTY_MAX = 4;
18
+ function penaltyOf(attempts) {
19
+ if (!attempts)
20
+ return null;
21
+ const total = Number(attempts.attempts);
22
+ const ok = Number(attempts.ok);
23
+ if (!Number.isFinite(total) || total <= 0)
24
+ return null;
25
+ if (!Number.isFinite(ok) || ok <= 0)
26
+ return LOSS_PENALTY_MAX;
27
+ return Math.min(LOSS_PENALTY_MAX, total / ok);
28
+ }
29
+ const ROUTE_SWITCH_SHARE = 1 / 3;
30
+ const SWITCH_GAIN_FLOOR_MS = 10;
31
+ const STALE_EVIDENCE_ROUNDS = 12;
32
+ const latency = new Map();
33
+ const samples = new Map();
34
+ const SAMPLE_WINDOW = 5;
35
+ let evidenceRound = 0;
36
+ const evidenceAtRound = new Map();
37
+ const lossPenalty = new Map();
38
+ const failurePenalty = new Map();
39
+ const foreign = new Set();
40
+ function norm(url) {
41
+ return String(url || '').trim().replace(/\/+$/, '');
42
+ }
43
+ function noteRouteLatency(url, ms, attempts) {
44
+ const key = norm(url);
45
+ if (!key)
46
+ return;
47
+ evidenceRound += 1;
48
+ if (typeof ms === 'number' && Number.isFinite(ms) && ms >= 0) {
49
+ latency.set(key, ms);
50
+ evidenceAtRound.set(key, evidenceRound);
51
+ const window = samples.get(key) ?? [];
52
+ window.push(ms);
53
+ samples.set(key, window.length > SAMPLE_WINDOW ? window.slice(window.length - SAMPLE_WINDOW) : window);
54
+ const penalty = penaltyOf(attempts);
55
+ if (penalty === null)
56
+ lossPenalty.delete(key);
57
+ else
58
+ lossPenalty.set(key, penalty);
59
+ failurePenalty.delete(key);
60
+ return;
61
+ }
62
+ samples.delete(key);
63
+ lossPenalty.delete(key);
64
+ noteRouteFailure(key);
65
+ }
66
+ function settledOf(key) {
67
+ const window = samples.get(key);
68
+ const ms = latency.get(key);
69
+ if (!window || window.length === 0)
70
+ return ms;
71
+ if (window.length === 1)
72
+ return window[0];
73
+ const sorted = [...window].sort((a, b) => a - b);
74
+ const mid = sorted.length >> 1;
75
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
76
+ }
77
+ const MIN_NOISE_SAMPLES = 2;
78
+ function sampleCountOf(key) {
79
+ return samples.get(key)?.length ?? 0;
80
+ }
81
+ function noiseBandOf(key) {
82
+ const window = samples.get(key);
83
+ if (!window || window.length < 2)
84
+ return 0;
85
+ let min = window[0];
86
+ let max = window[0];
87
+ for (const value of window) {
88
+ if (value < min)
89
+ min = value;
90
+ if (value > max)
91
+ max = value;
92
+ }
93
+ return (max - min) / 2;
94
+ }
95
+ function noteRouteFailure(url) {
96
+ const key = norm(url);
97
+ if (!key)
98
+ return;
99
+ const prev = failurePenalty.get(key) ?? 1;
100
+ failurePenalty.set(key, Math.min(FAILURE_PENALTY_MAX, prev * FAILURE_PENALTY_STEP));
101
+ }
102
+ function isFresh(key, threshold = STALE_EVIDENCE_ROUNDS) {
103
+ const at = evidenceAtRound.get(key);
104
+ return typeof at === 'number' && evidenceRound - at <= threshold;
105
+ }
106
+ function staleThresholdFor(routeCount) {
107
+ const perRound = Math.max(6, routeCount);
108
+ return STALE_EVIDENCE_ROUNDS * Math.max(1, Math.ceil(perRound / 6));
109
+ }
110
+ function settledCostOf(key) {
111
+ const ms = settledOf(key);
112
+ if (ms === undefined)
113
+ return undefined;
114
+ return ms * (lossPenalty.get(key) ?? 1) * (failurePenalty.get(key) ?? 1);
115
+ }
116
+ function noiseCostOf(key) {
117
+ return noiseBandOf(key) * (lossPenalty.get(key) ?? 1) * (failurePenalty.get(key) ?? 1);
118
+ }
119
+ const SETTLE_ROUNDS = 4;
120
+ let lastSwitch = null;
121
+ function costOf(url) {
122
+ const key = norm(url);
123
+ const ms = latency.get(key);
124
+ if (ms === undefined)
125
+ return undefined;
126
+ return ms * (lossPenalty.get(key) ?? 1) * (failurePenalty.get(key) ?? 1);
127
+ }
128
+ function noteRouteForeign(url) {
129
+ const key = norm(url);
130
+ if (key)
131
+ foreign.add(key);
132
+ }
133
+ function isRouteForeign(url) {
134
+ return foreign.has(norm(url));
135
+ }
136
+ function routeLatencyOf(url) {
137
+ const value = latency.get(norm(url));
138
+ return typeof value === 'number' ? value : null;
139
+ }
140
+ function routeCostOf(url) {
141
+ const value = costOf(url);
142
+ return typeof value === 'number' ? value : null;
143
+ }
144
+ function forgetRouteFacts() {
145
+ latency.clear();
146
+ samples.clear();
147
+ lossPenalty.clear();
148
+ failurePenalty.clear();
149
+ evidenceAtRound.clear();
150
+ foreign.clear();
151
+ lastSwitch = null;
152
+ }
153
+ function orderRouteCandidates(routes, currentUrl = '', suspended = []) {
154
+ const current = norm(currentUrl);
155
+ const foreignFree = routes.filter((route) => !foreign.has(norm(route.url)));
156
+ const cooling = new Set((suspended || []).map(norm).filter(Boolean));
157
+ const allCooling = foreignFree.length > 0 && foreignFree.every((route) => cooling.has(norm(route.url)));
158
+ const cool = allCooling ? new Set() : cooling;
159
+ const warm = foreignFree.filter((route) => !cool.has(norm(route.url)));
160
+ const cold = foreignFree.filter((route) => cool.has(norm(route.url)));
161
+ const staleThreshold = staleThresholdFor(warm.length);
162
+ const known = warm
163
+ .filter((route) => latency.has(norm(route.url)) && isFresh(norm(route.url), staleThreshold))
164
+ .sort((a, b) => settledCostOf(norm(a.url)) - settledCostOf(norm(b.url)));
165
+ const unknown = warm.filter((route) => !(latency.has(norm(route.url)) && isFresh(norm(route.url), staleThreshold)));
166
+ const ordered = [...known, ...unknown, ...cold];
167
+ const at = ordered.findIndex((route) => norm(route.url) === current);
168
+ if (at < 0)
169
+ return ordered;
170
+ if (at === 0)
171
+ return ordered;
172
+ if (cool.has(current))
173
+ return ordered;
174
+ const currentCost = isFresh(current, staleThreshold) ? settledCostOf(current) : undefined;
175
+ if (currentCost === undefined)
176
+ return ordered;
177
+ const headUrl = norm(ordered[0].url);
178
+ const headCost = settledCostOf(headUrl);
179
+ const settleRounds = SETTLE_ROUNDS * Math.max(1, Math.ceil(warm.length / 6));
180
+ if (lastSwitch && evidenceRound - lastSwitch.round > settleRounds)
181
+ lastSwitch = null;
182
+ const bouncingBack = Boolean(lastSwitch && lastSwitch.to === current && lastSwitch.from === headUrl);
183
+ const enoughEvidence = sampleCountOf(current) >= MIN_NOISE_SAMPLES
184
+ && sampleCountOf(headUrl) >= MIN_NOISE_SAMPLES;
185
+ const gain = headCost !== undefined ? currentCost - headCost : 0;
186
+ const noise = enoughEvidence ? noiseCostOf(current) + noiseCostOf(headUrl) : 0;
187
+ const required = Math.max(noise, currentCost * ROUTE_SWITCH_SHARE, SWITCH_GAIN_FLOOR_MS);
188
+ const worthwhile = headCost !== undefined && gain > required;
189
+ const decisive = gain > required * 2;
190
+ const settled = !bouncingBack || decisive;
191
+ if (settled && worthwhile) {
192
+ lastSwitch = { from: current, to: headUrl, round: evidenceRound };
193
+ return ordered;
194
+ }
195
+ const [item] = ordered.splice(at, 1);
196
+ ordered.unshift(item);
197
+ return ordered;
198
+ }
199
+
200
+ return exports;
201
+ }
202
+ module.exports = { createRoutePolicy, ...createRoutePolicy() };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-plugin",
3
- "version": "0.5.52",
3
+ "version": "0.5.53",
4
4
  "description": "Mobile API (/api/mobile/v1) and relay client for the DSH mobile app — desktop profile build (dsh 0.2.x, peers resolved by the host)",
5
5
  "license": "MIT",
6
6
  "icon": "./icon.png",
@@ -48,6 +48,7 @@
48
48
  "lib/**/*.cjs",
49
49
  "lib/**/*.html",
50
50
  "lib/**/package.json",
51
+ "native/**",
51
52
  "dsh-mobile-credentials",
52
53
  "locale/*.json",
53
54
  "icon.png",
@@ -73,11 +74,11 @@
73
74
  "ws": "8.18.0"
74
75
  },
75
76
  "optionalDependencies": {
76
- "dsh-mobile-tailcat-darwin-arm64": "1.1.1",
77
- "dsh-mobile-tailcat-darwin-x64": "1.1.1",
78
- "dsh-mobile-tailcat-linux-arm64": "1.1.1",
79
- "dsh-mobile-tailcat-linux-x64": "1.1.1",
80
- "dsh-mobile-tailcat-win32-x64": "1.1.1"
77
+ "dsh-mobile-tailcat-darwin-arm64": "1.1.2",
78
+ "dsh-mobile-tailcat-darwin-x64": "1.1.2",
79
+ "dsh-mobile-tailcat-linux-arm64": "1.1.2",
80
+ "dsh-mobile-tailcat-linux-x64": "1.1.2",
81
+ "dsh-mobile-tailcat-win32-x64": "1.1.2"
81
82
  },
82
83
  "peerDependencies": {
83
84
  "@deepseek-ai/cordis": ">=4.0.1",