dsh-mobile-plugin 0.5.88 → 0.5.91

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 (68) hide show
  1. package/config/agent-presets/standard/agent.cordis.yml +5 -0
  2. package/config/agent-presets/standard/skills/dsh-mobile-kb/SKILL.md +54 -0
  3. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/ipv4.md +38 -0
  4. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/ipv6.md +36 -0
  5. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/network.md +27 -0
  6. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/offline.md +30 -0
  7. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/pairing.md +27 -0
  8. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/relay.md +23 -0
  9. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/selfhost-common.md +44 -0
  10. package/docs/extension-authoring.md +24 -8
  11. package/extension-registry/index.json +19 -1
  12. package/host.js +7 -15
  13. package/lib/client.js +151 -40
  14. package/lib/host-compat.cjs +4 -1
  15. package/lib/host-preset-patches.cjs +40 -0
  16. package/lib/impl.js +39 -35
  17. package/lib/index.js +3 -0
  18. package/lib/mobile/agent-presets.js +12 -0
  19. package/lib/mobile/answer-sources.js +3 -2
  20. package/lib/mobile/approval-facts.js +26 -3
  21. package/lib/mobile/approvals.js +42 -11
  22. package/lib/mobile/archive-clean.js +5 -0
  23. package/lib/mobile/extension-catalog.js +29 -3
  24. package/lib/mobile/extension-dev.js +7 -0
  25. package/lib/mobile/extension-metadata.cjs +40 -0
  26. package/lib/mobile/feedback-read.cjs +59 -0
  27. package/lib/mobile/feedback.js +24 -16
  28. package/lib/mobile/history-derive.js +3 -7
  29. package/lib/mobile/host-bridge/shims.js +20 -3
  30. package/lib/mobile/host-bridge.js +30 -1
  31. package/lib/mobile/live-steps.js +4 -3
  32. package/lib/mobile/mux.js +30 -3
  33. package/lib/mobile/permissions.js +30 -0
  34. package/lib/mobile/plugin-catalog.js +5 -0
  35. package/lib/mobile/plugin-self.js +4 -0
  36. package/lib/mobile/questions.js +21 -2
  37. package/lib/mobile/relay-control.js +67 -3
  38. package/lib/mobile/session-cache.js +12 -1
  39. package/lib/mobile/session-models.js +1 -0
  40. package/lib/mobile/session-presets.js +5 -2
  41. package/lib/mobile/session-send.js +12 -2
  42. package/lib/mobile/session-step.js +3 -2
  43. package/lib/mobile/stats-collect.cjs +26 -8
  44. package/lib/mobile/step-index.js +4 -3
  45. package/lib/mobile/stream-registry.js +29 -4
  46. package/lib/mobile/subagents.js +1 -1
  47. package/lib/mobile/third-party-extensions.js +6 -1
  48. package/lib/mobile/tool-result-state.js +12 -0
  49. package/lib/panel/index.html +27 -26
  50. package/lib/relay/identity-rotate.cjs +4 -1
  51. package/lib/relay/lan-discovery.cjs +18 -3
  52. package/lib/relay/lan-proxy.js +22 -2
  53. package/lib/relay/preview.js +10 -1
  54. package/lib/relay/protocol.js +2 -2
  55. package/lib/relay/tunnel.js +7 -2
  56. package/lib/remote/controller.cjs +4 -1
  57. package/lib/remote/tunnel-helper.cjs +2 -2
  58. package/lib/routes/control-plane.js +34 -13
  59. package/lib/routes/feedback.cjs +20 -0
  60. package/lib/session-cleanup.cjs +17 -0
  61. package/lib/shared/route-order.cjs +6 -0
  62. package/lib/shared/session-storage.cjs +82 -0
  63. package/lib/shell/first-install.js +102 -0
  64. package/lib/shell/updater.js +6 -5
  65. package/lib/sidecar-facade-worker.cjs +10 -2
  66. package/lib/sidecar-lifecycle.cjs +94 -14
  67. package/lib/tailcat/wiring.cjs +2 -2
  68. package/package.json +3 -2
@@ -1,3 +1,4 @@
1
+ // 换身份同时迁移设备凭据与连接登记,连续换号后仍能准确吊销。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -12,16 +13,18 @@
12
13
  *
13
14
  * 放在这里而不是装配层:装配层只把它挂上,不许多长实现(见 `test/assembly-layer.test.cjs`)。
14
15
  */
15
- function createIdentityRotator({ state, rotateIdentity, saveState, syncSidecar, syncControl, migrateCredentials }) {
16
+ function createIdentityRotator({ state, rotateIdentity, saveState, syncSidecar, syncControl, migrateCredentials, migrateConnections }) {
16
17
  let rotating = false;
17
18
  return async function rotateIdentityNow() {
18
19
  if (rotating) return;
19
20
  rotating = true;
20
21
  try {
22
+ const previousInstanceId = state.instanceId;
21
23
  const { instanceId } = rotateIdentity(state);
22
24
  saveState(state);
23
25
  // 迁移失败不阻断换号:鉴权仍认旧号,最坏退回「重扫」,不会把本机卡在冲突里。
24
26
  try { if (typeof migrateCredentials === 'function') migrateCredentials(instanceId); } catch { /* ignore */ }
27
+ if (typeof migrateConnections === 'function') migrateConnections(previousInstanceId, instanceId);
25
28
  try { await syncSidecar(); } catch { /* 配置下发失败不影响重连,下次 sync 再补 */ }
26
29
  try { syncControl(); } catch { /* ignore */ }
27
30
  } finally {
@@ -1,4 +1,4 @@
1
- // 短暂占用先重试原端口,固定入口禁止自动换号。
1
+ // 短暂占用先重试原端口;发现重发等待退订结束,失败保留底层原因。
2
2
  'use strict';
3
3
  // 只发布已监听入口;发布失败时停止换号,现有固定入口仍可使用。
4
4
  const { canChangeLanPort } = require('./lan-port-policy.cjs');
@@ -13,6 +13,8 @@ function createLanDiscovery({ instanceId, onChange = () => {}, makeBonjour = onE
13
13
  let service = null;
14
14
  let generation = 0;
15
15
  let cancelPending = null;
16
+ let detachErrors = null;
17
+ let stopping = null;
16
18
  let view = { state: 'off', error: null };
17
19
  const set = (state, error = null) => { view = { state, error }; onChange(); };
18
20
  const stop = () => {
@@ -21,10 +23,14 @@ function createLanDiscovery({ instanceId, onChange = () => {}, makeBonjour = onE
21
23
  cancelPending = null;
22
24
  const oldService = service;
23
25
  const oldClient = client;
26
+ const oldDetachErrors = detachErrors;
24
27
  service = null;
25
28
  client = null;
29
+ detachErrors = null;
26
30
  set('off');
27
- return new Promise(resolve => {
31
+ if (stopping) return stopping;
32
+ if (!oldClient && !oldService) return Promise.resolve();
33
+ const closing = new Promise(resolve => {
28
34
  let settled = false;
29
35
  const timer = setTimeout(finish, 300);
30
36
  function finish() {
@@ -32,6 +38,7 @@ function createLanDiscovery({ instanceId, onChange = () => {}, makeBonjour = onE
32
38
  settled = true;
33
39
  clearTimeout(timer);
34
40
  try { oldClient?.destroy(); } catch { /* 已退出 */ }
41
+ oldDetachErrors?.();
35
42
  resolve();
36
43
  }
37
44
  try {
@@ -39,6 +46,8 @@ function createLanDiscovery({ instanceId, onChange = () => {}, makeBonjour = onE
39
46
  else finish();
40
47
  } catch { finish(); }
41
48
  });
49
+ stopping = closing.finally(() => { stopping = null; });
50
+ return stopping;
42
51
  };
43
52
  const publish = async port => {
44
53
  const stopped = stop();
@@ -67,6 +76,11 @@ function createLanDiscovery({ instanceId, onChange = () => {}, makeBonjour = onE
67
76
  timer = setTimeout(() => fail(new Error('局域网发现发布超时')), timeoutMs);
68
77
  try {
69
78
  client = makeBonjour(fail);
79
+ const mdns = client.server?.mdns;
80
+ if (mdns) {
81
+ mdns.on('error', fail);
82
+ detachErrors = () => mdns.removeListener('error', fail);
83
+ }
70
84
  service = client.publish({ name: `DSH-${instanceId}`, type: SERVICE_TYPE, protocol: 'tcp', host: `dsh-${instanceId}.local`, port,
71
85
  txt: { id: instanceId, v: '1' } });
72
86
  service.once('up', () => finish(true));
@@ -105,9 +119,10 @@ async function bindLanEndpoint({ requestedPort, createProxy, discovery, store, i
105
119
  const port = proxy.port();
106
120
  const published = await discovery.publish(port);
107
121
  if (!isCurrent() || (changed && !published)) {
122
+ const discoveryError = discovery.snapshot?.().error;
108
123
  await proxy.stop();
109
124
  await discovery.stop();
110
- throw new Error(changed ? '新端口已释放:局域网发现不可用,保留原端口配置,请释放占用后重试。' : '局域网配置已更新');
125
+ throw new Error(changed ? `新端口已释放:局域网发现不可用${discoveryError ? `(${discoveryError})` : ''},保留原端口配置,请释放占用后重试。` : '局域网配置已更新');
111
126
  }
112
127
  return { proxy, port, changed };
113
128
  }
@@ -76,6 +76,8 @@ function createLanProxy(opts) {
76
76
  lanSecret,
77
77
  upstreamPort,
78
78
  upstreamHost = '127.0.0.1',
79
+ // 用户手填的直连地址(穿透域名 / 公网 IP):经第三方穿透落到本代理的请求用它判通道。
80
+ manualLanUrl = '',
79
81
  onLog = () => {},
80
82
  /**
81
83
  * 桌面用户授权回调:async (device) => ({ approved, token? })。
@@ -94,6 +96,24 @@ function createLanProxy(opts) {
94
96
  maxUpstreamSse = MAX_UPSTREAM_SSE_CONNECTIONS,
95
97
  } = opts;
96
98
 
99
+ // 手填直连地址的 host。经第三方穿透(frpc 等)落到本代理的请求,Host 是穿透域名而不是
100
+ // 局域网那台的 IP;不区分就会把「外网穿透」在设备列表里显示成「局域网」,排查直接被带偏。
101
+ const manualDirectHost = (() => {
102
+ try { return manualLanUrl ? new URL(manualLanUrl).hostname.toLowerCase() : '' } catch { return '' }
103
+ })();
104
+ /** 这条请求实际从哪条通道来:命中手填直连的 Host 记 direct,否则按监听族分 ipv6 / lan。 */
105
+ const channelFor = (req) => {
106
+ if (manualDirectHost) {
107
+ const host = String(req?.headers?.host || '').trim();
108
+ if (host) {
109
+ try {
110
+ if (new URL(`http://${host}`).hostname.toLowerCase() === manualDirectHost) return 'direct';
111
+ } catch { /* 非法 Host 当没命中 */ }
112
+ }
113
+ }
114
+ return req?.socket?.localFamily === 'IPv6' ? 'ipv6' : 'lan';
115
+ };
116
+
97
117
  const inboundSockets = new Set();
98
118
  const trackSocket = socket => { inboundSockets.add(socket); socket.once('close', () => inboundSockets.delete(socket)); };
99
119
  let server = null;
@@ -398,7 +418,7 @@ function createLanProxy(opts) {
398
418
  }
399
419
  const headers = withViaHeader(
400
420
  Object.fromEntries(Object.entries(req.headers).filter(([k]) => !HOP_BY_HOP.has(k))),
401
- req.socket?.localFamily === 'IPv6' ? 'ipv6' : 'lan',
421
+ channelFor(req),
402
422
  `${formatHost(upstreamHost)}:${upstreamPort}`,
403
423
  );
404
424
  const isSse = String(req.headers.accept || '').toLowerCase().includes('text/event-stream');
@@ -509,7 +529,7 @@ function createLanProxy(opts) {
509
529
 
510
530
  const headers = withViaHeader(
511
531
  Object.fromEntries(Object.entries(req.headers).filter(([key, value]) => !HOP_BY_HOP.has(key) && value !== undefined)),
512
- req.socket?.localFamily === 'IPv6' ? 'ipv6' : 'lan',
532
+ channelFor(req),
513
533
  `${formatHost(upstreamHost)}:${upstreamPort}`,
514
534
  );
515
535
  // 上游要认得这条请求:新 T1 记录没有存下来的宿主令牌,就把请求里出示的那一枚
@@ -1,4 +1,4 @@
1
- // 连接既有预览目标,并为宿主网页版逐请求标记可信转发来源。
1
+ // 预览连接归属随本机换号迁移,宿主网页版逐请求标记可信转发来源。
2
2
  'use strict';
3
3
 
4
4
  /**
@@ -542,8 +542,17 @@ function createPreviewService({ authorized, protectedPorts, ownWebPort = () => n
542
542
  return selected.length;
543
543
  };
544
544
 
545
+ const reassignInstance = (fromInstanceId, toInstanceId) => {
546
+ const from = String(fromInstanceId || '');
547
+ const to = String(toInstanceId || '');
548
+ for (const identity of deviceConnections.values()) {
549
+ if (identity.instanceId === from) identity.instanceId = to;
550
+ }
551
+ };
552
+
545
553
  return {
546
554
  handleUpgrade,
555
+ reassignInstance,
547
556
  dropDevice: (deviceId, instanceId, deferClose) => dropConnections(deviceId, instanceId, deferClose),
548
557
  dropAll: (instanceId) => dropConnections(undefined, instanceId),
549
558
  /** 「预览碰过哪些端口」的快照,供状态接口展示。 */
@@ -1,4 +1,4 @@
1
- // 注册字段与关闭原因同步 relay-core 协议说明,blobPut 旧 id0 与协商 idN 语义保持。
1
+ // 控制错误id0说明与relay-core同步,保留帧和普通请求编号语义不变。
2
2
  'use strict';
3
3
 
4
4
  /**
@@ -28,7 +28,7 @@ const T = {
28
28
  httpError: 0x09, // id=N JSON {message}
29
29
  wsUpgrade: 0x0A, // id=N JSON {path, headers}
30
30
  wsOpen: 0x0B, // id=N 空
31
- wsError: 0x0C, // id=N JSON {message}
31
+ wsError: 0x0C, // id=N 上游错误{message};id=0 中转拒绝{message,code?},code可为bad_register_secret/plugin_too_old/instance_mismatch;准入拒绝可无code
32
32
  wsText: 0x0D, // id=N raw bytes(上游 WS 文本帧数据)
33
33
  wsBinary: 0x0E, // id=N raw bytes(上游 WS 二进制帧数据)
34
34
  wsClose: 0x0F, // id=N 2B 大端 close code + 可选 UTF-8 reason(最多 123B)
@@ -1,4 +1,4 @@
1
- // 心跳超时原因随关闭回调保留,供连接状态区分本机超时和对端断开。
1
+ // 空心跳帧有独立且有界的队列余量,普通数据背压不关闭共享隧道。
2
2
  // 注册取消与单调心跳保持原语义,blob逐片确认独立于HTTP/WS请求。
3
3
  'use strict';
4
4
  // 中转隧道把请求转给宿主 web 服务时,上游地址跟随宿主实际绑定地址(可能不是回环)。
@@ -38,6 +38,8 @@ const HEARTBEAT_INTERVAL_MS = 15_000;
38
38
  // 白等一次响应头超时才见到失败。45s = 三拍 ping 都没回,迟到的 pong 与调度抖动还容得下。
39
39
  const PONG_TIMEOUT_MS = 45_000;
40
40
  const MAX_TUNNEL_BUFFERED_BYTES = 16 * 1024 * 1024;
41
+ // 仅空 PING/PONG 可用;仍进同一 FIFO,不绕过已入队数据。
42
+ const HEARTBEAT_BUFFER_ALLOWANCE_BYTES = 1024;
41
43
  const TUNNEL_BUFFER_LOW_WATER_BYTES = MAX_TUNNEL_BUFFERED_BYTES / 2;
42
44
  const HTTP_RESPONSE_CHUNK_BYTES = 256 * 1024;
43
45
  const MAX_HTTP_RESPONSE_PENDING_BYTES = 8 * 1024 * 1024;
@@ -162,7 +164,10 @@ class RelayTunnel {
162
164
  trySendEncodedFrame(frame) {
163
165
  if (!this.connected) return 'unavailable';
164
166
  const buffered = Number(this.ws.bufferedAmount || 0);
165
- if (buffered > MAX_TUNNEL_BUFFERED_BYTES || buffered + frame.length > MAX_TUNNEL_BUFFERED_BYTES) {
167
+ const emptyHeartbeat = frame.length === 9 && frame.readUInt32BE(1) === 0 && frame.readUInt32BE(5) === 0
168
+ && (frame[0] === T.ping || frame[0] === T.pong);
169
+ const limit = MAX_TUNNEL_BUFFERED_BYTES + (emptyHeartbeat ? HEARTBEAT_BUFFER_ALLOWANCE_BYTES : 0);
170
+ if (buffered > limit || buffered + frame.length > limit) {
166
171
  this.dropOverBudget(buffered, frame.length);
167
172
  return 'backpressure';
168
173
  }
@@ -1,4 +1,4 @@
1
- // 远程电脑状态保留环境诊断,助手换代主动撤下隧道并恢复现有访问。
1
+ // 远端终止授权同步回收设备隧道,助手换代保持有效访问恢复。
2
2
  // 2026-11-19:桌面窗口改成多窗口集合(只有最后一个窗口退出才回到未打开),进程还在就显示正在打开 /
3
3
  // 已打开;换网按 lost 与非 lost 分流,lost 只断开已打开设备的连接、不改状态也不探活,非 lost 让所有
4
4
  // 绑定(含没打开过的)都重选线路;connect 回调记下 connection.route 作为「实际在用线路」供面板展示;
@@ -62,11 +62,14 @@ function createRemoteController({ store, transport, name, tunnels, onBindingsCha
62
62
  }
63
63
 
64
64
  function fault(item, error) {
65
+ if (item.state === 'revoked' || item.state === 'expired') return;
65
66
  item.lastError = safeError(error); item.lastErrorCode = error?.code || 'REMOTE_CONNECT';
66
67
  if (error?.code === 'REMOTE_REVOKED') {
67
68
  item.state = 'revoked'; item.gateway?.close(); item.gateway = null; item.activeRoute = null; item.router.close();
69
+ void Promise.resolve(tunnels?.close?.(item.binding.id)).catch(() => {});
68
70
  } else if (error?.code === 'REMOTE_EXPIRED') {
69
71
  item.state = 'expired'; item.gateway?.close(); item.gateway = null; item.activeRoute = null; item.router.close();
72
+ void Promise.resolve(tunnels?.close?.(item.binding.id)).catch(() => {});
70
73
  } else if (item.state !== 'expired' && item.state !== 'revoked') item.state = 'offline';
71
74
  }
72
75
 
@@ -1,4 +1,4 @@
1
- // 桌面助手 RPC 按请求关联,意外退出后退避重拉并通知候选持有者。
1
+ // 桌面助手 RPC 仅在明确不支持时停用,能力探测超时按现有退避恢复。
2
2
  'use strict';
3
3
 
4
4
  const { spawn } = require('node:child_process');
@@ -112,7 +112,7 @@ function createRemoteTunnelHelper(options = {}) {
112
112
  return new Promise((resolve, reject) => {
113
113
  const timer = setTimeout(() => {
114
114
  pending.delete(requestId);
115
- const code = command === 'remoteCapabilities' ? 'remote-helper-unsupported' : 'remote-helper-timeout';
115
+ const code = command === 'remoteCapabilities' ? 'remote-helper-capability-timeout' : 'remote-helper-timeout';
116
116
  reject(failure(code));
117
117
  if (fields.deviceId && child === proc && proc.stdin?.writable) {
118
118
  proc.stdin.write(`${JSON.stringify({ command: 'remoteClose', requestId: randomUUID(), deviceId: fields.deviceId })}\n`);
@@ -1,4 +1,5 @@
1
- // 局域网扫码绑定成功记录完成时间;本机端口与穿透依赖仍由宿主统一判定。
1
+ // 配对二维码在隧道窗口就绪后取当前状态,渲染完成前复核票据与身份。
2
+ // 网络动作区分配置受理与真实连接,主动重连使用独立动作并保留探测总期限。
2
3
  // 注册本机控制面,并在吊销回执完成后关闭本实例在途连接。
3
4
  // 本机面板读取上报目的地,FRP 仅在明确保存后启动,停用清除直连目标。
4
5
  'use strict';
@@ -52,6 +53,7 @@ const { clearCompletionForAllDevices, invalidateSessionList } = require('../mobi
52
53
  const { recordSessionRead } = require('../mobile/session-last-turn.js');
53
54
  // 收件目录的占用与清理:和移动端那条路由是同一份实现(`lib/mobile/inbox-clean.js`)。
54
55
  const { scanInbox, clearInbox, usageView, setAutoClear } = require('../mobile/inbox-clean.js');
56
+ const { handleFeedback } = require('./feedback.cjs');
55
57
 
56
58
  /** 一次 desktop-read 上报最多带多少个会话 id(防灌爆;客户端半边一次最多也就几个)。 */
57
59
  const MAX_DESKTOP_READ_IDS = 200;
@@ -296,6 +298,7 @@ function registerControlPlaneRoutes(deps) {
296
298
  status: rawStatus,
297
299
  settings,
298
300
  syncSidecar,
301
+ reconnectTunnel,
299
302
  getSidecar,
300
303
  credentials,
301
304
  activeGuard,
@@ -387,6 +390,9 @@ function registerControlPlaneRoutes(deps) {
387
390
  sendJson,
388
391
  });
389
392
 
393
+ registerRoute({ kind: 'exact', path: '/api/relay/feedback', handler: localOnly(['GET', 'POST'], (req, res) =>
394
+ handleFeedback({ req, res, readJson, sendJson, credentials, instanceId: () => state.instanceId })) });
395
+
390
396
  // Pairing approval. The desktop shell used to answer this with an interactive
391
397
  // prompt; a headless host has no surface for one, so `pairingPolicy` decides.
392
398
  // Both transports funnel through here — the relay forwards `pairRequest` and
@@ -504,27 +510,25 @@ function registerControlPlaneRoutes(deps) {
504
510
  .map((u) => u.trim().replace(/\/+$/, ''))
505
511
  const results = await Promise.all(targets.map(async (url) => {
506
512
  const started = Date.now()
513
+ const controller = new AbortController()
514
+ const timer = setTimeout(() => controller.abort(), RELAY_PROBE_TIMEOUT_MS)
507
515
  try {
508
- const controller = new AbortController()
509
- const timer = setTimeout(() => controller.abort(), RELAY_PROBE_TIMEOUT_MS)
510
516
  const response = await fetch(`${url}/healthz`, { signal: controller.signal, redirect: 'follow' })
511
517
  // 读完响应体再停表:只等到响应头会把「连得上但发不出东西」算成很快。
512
518
  const text = await response.text().catch(() => '')
513
- if (!response.ok) {
514
- clearTimeout(timer)
515
- return { url, ms: null }
516
- }
519
+ if (!response.ok) return { url, ms: null }
517
520
  // **只认运维意义上「这一台确实是中转」**:`/healthz` 回 200 的站点满互联网都是,
518
521
  // 光看它等于把随便一个域名也当可用中转。
519
522
  // 中转自己那条地址体检 `/api/mobile/v1/health` 会带回 `service`,对不上就不是它。
520
523
  const who = await fetch(`${url}/api/mobile/v1/health`, { signal: controller.signal, redirect: 'follow' })
521
524
  .then((r) => (r.ok ? r.json() : null))
522
525
  .catch(() => null)
523
- clearTimeout(timer)
524
526
  if (!who || who.service !== 'dsh-mobile-relay') return { url, ms: null }
525
527
  return { url, ms: Date.now() - started, service: who.service, version: who.version }
526
528
  } catch {
527
529
  return { url, ms: null }
530
+ } finally {
531
+ clearTimeout(timer)
528
532
  }
529
533
  }))
530
534
  sendJson(res, 200, { ok: true, results })
@@ -635,7 +639,7 @@ function registerControlPlaneRoutes(deps) {
635
639
  }
636
640
  const current = typeof deps.frp.status === 'function' ? deps.frp.status() : started
637
641
  const sameRun = deps.frp.runId === runId
638
- const ok = Boolean(sameRun && current && current.running && !current.error)
642
+ const ok = Boolean(sameRun && current && ((current.running && !current.error) || current.retrying || current.starting))
639
643
  sendJson(res, 200, { ok, status: sameRun ? current : { ...current, running: false, remoteAddress: '' } })
640
644
  }) })
641
645
  registerRoute({ kind: 'exact', path: '/api/relay/frp/stop', handler: localOnly('POST', async (_req, res) => {
@@ -791,14 +795,20 @@ function registerControlPlaneRoutes(deps) {
791
795
  const previewUrl = preview && /^https?:\/\/[^\s]+$/i.test(preview.trim())
792
796
  ? preview.trim().replace(/\/+$/, '')
793
797
  : ''
794
- const source = previewUrl ? { ...state, relayUrl: previewUrl, relayUrls: [previewUrl] } : state
795
- const { payload } = pairingPayload(source, lanPortInUse())
796
798
  // 直连隧道:这一个是「不配中转也能连」的那条路。窗口是现开的一次性小节点(两分钟、
797
799
  // 只放行当场那把钥匙),开不出来就照旧只给局域网与中转——所以它永远只是加一条路,
798
800
  // 不会让原来那套配不上。
799
801
  const tailcat = deps.tailcat && typeof deps.tailcat.openPairingWindow === 'function'
800
802
  ? await deps.tailcat.openPairingWindow(120).catch(() => null)
801
803
  : null
804
+ // 开窗口会等待助手响应;期间手动换码、配对成功或换身份都可能更新票据。
805
+ // 地址、身份与票据一起从等待后的同一份状态生成,不能把旧票据带进新二维码。
806
+ if (!state.enabled) {
807
+ sendJson(res, 409, { ok: false, error: '请先启用远程控制并保存配置' })
808
+ return
809
+ }
810
+ const source = previewUrl ? { ...state, relayUrl: previewUrl, relayUrls: [previewUrl] } : state
811
+ const { payload } = pairingPayload(source, lanPortInUse())
802
812
  if (tailcat) {
803
813
  payload.tailcat = {
804
814
  version: 1,
@@ -844,6 +854,10 @@ function registerControlPlaneRoutes(deps) {
844
854
  margin: 4,
845
855
  width: 1024,
846
856
  })
857
+ if (!state.enabled || payload.instanceId !== state.instanceId || payload.code !== state.pairingCode || payload.ticket !== (state.pairingTicket || '')) {
858
+ sendJson(res, 409, { ok: false, error: '配对状态已更新,请重新获取二维码' })
859
+ return
860
+ }
847
861
  sendJson(res, 200, {
848
862
  ok: true,
849
863
  name: payload.name,
@@ -1071,8 +1085,13 @@ function registerControlPlaneRoutes(deps) {
1071
1085
  sendJson(res, 200, await connectionCheck.run({ force }))
1072
1086
  }) })
1073
1087
  registerRoute({ kind: 'exact', path: '/api/relay/reconnect', handler: localOnly('POST', async (_req, res) => {
1074
- await syncSidecar()
1075
- sendJson(res, 200, status())
1088
+ if (typeof reconnectTunnel !== 'function') return sendJson(res, 503, { ok: false, error: { code: 'unavailable', message: '当前后台服务不支持主动重连' } })
1089
+ try {
1090
+ await reconnectTunnel()
1091
+ sendJson(res, 200, status())
1092
+ } catch (error) {
1093
+ sendJson(res, 502, { ok: false, error: { code: 'reconnect-failed', message: error instanceof Error ? error.message : String(error) } })
1094
+ }
1076
1095
  }) })
1077
1096
  // ── 插件更新 ──
1078
1097
  //
@@ -1330,6 +1349,7 @@ const WEB_ACCESS_ROUTES = new Set([
1330
1349
  '/api/relay/faults',
1331
1350
  // 配对二维码含一次性票据,同时受 LOCAL_OPERATOR_ROUTES 限制;本机及局域网直连可取,公网窗口不放行。
1332
1351
  '/api/relay/pairing',
1352
+ '/api/relay/feedback',
1333
1353
  '/api/relay/toggle',
1334
1354
  '/api/relay/regenerate',
1335
1355
  '/api/relay/onboarded',
@@ -1378,6 +1398,7 @@ const WEB_ACCESS_ROUTES = new Set([
1378
1398
  */
1379
1399
  const LOCAL_OPERATOR_ROUTES = new Set([
1380
1400
  '/api/relay/pairing',
1401
+ '/api/relay/feedback',
1381
1402
  '/api/relay/toggle',
1382
1403
  '/api/relay/regenerate',
1383
1404
  '/api/relay/config',
@@ -0,0 +1,20 @@
1
+ // 用途:本机与局域网控制面读取反馈、续回复;业务复用统一反馈服务。
2
+ 'use strict';
3
+
4
+ const { readFeedback, submitFeedback } = require('../mobile/feedback.js');
5
+
6
+ async function handleFeedback({ req, res, readJson, sendJson, credentials, instanceId }) {
7
+ try {
8
+ if (req.method === 'GET') {
9
+ const key = new URL(req.url, 'http://localhost').searchParams.get('thread_key');
10
+ return sendJson(res, 200, await readFeedback(key));
11
+ }
12
+ const body = await readJson(req);
13
+ const submitted = await submitFeedback({ credentials, instanceId }, body.content, body.threadKey);
14
+ return sendJson(res, 200, submitted);
15
+ } catch (error) {
16
+ return sendJson(res, error.status || 502, { ok: false, error: { code: 'feedback_failed', message: String(error?.message || error) } });
17
+ }
18
+ }
19
+
20
+ module.exports = { handleFeedback };
@@ -1,3 +1,4 @@
1
+ // 永久清理只处理已确认的 JSONL 路由,SQLite 队列与归档状态保留。
1
2
  /**
2
3
  * 会话数据清理:按 sessionId 删除 dshHome 下的 sessions/** 目录与 project cache。
3
4
  *
@@ -39,6 +40,7 @@ const { rememberDeletedSessionIds } = require('./mobile/session-cache.js')
39
40
  const { collectStats, DELETING_COLLECT_BUDGET_MS } = require('./mobile/stats-collect.cjs')
40
41
  // 收件目录的启动清理与这里共用同一个「宿主刚起来」的窗口,实现见 mobile/inbox-clean.js。
41
42
  const { clearInboxOnce } = require('./mobile/inbox-clean.js')
43
+ const { assertSessionCleanupSupported, assertSessionCleanupStillJsonl } = require('./shared/session-storage.cjs')
42
44
 
43
45
  function asItems(response) {
44
46
  const value = envelopeValue(response)
@@ -312,9 +314,21 @@ async function collectBeforeDelete(ctx, sessionIds, log) {
312
314
  async function deleteQueuedArchivedSessions(log, ctx) {
313
315
  const queued = readPendingArchivedClearIds()
314
316
  if (queued.length === 0) return { deleted: [], kept: [] }
317
+ try {
318
+ await assertSessionCleanupSupported(ctx, queued)
319
+ } catch (error) {
320
+ log?.(`archived clear queue: ${error.message}`)
321
+ return { deleted: [], kept: queued }
322
+ }
315
323
  // 删之前先给这批 id 补一刀统计:入队到这次启动之间可能隔着一次重启,那段时间里
316
324
  // 会话完全可能继续被用,而那一截用量只有这一刻才采得到(见 `collectBeforeDelete`)。
317
325
  await collectBeforeDelete(ctx, queued, log)
326
+ try {
327
+ await assertSessionCleanupStillJsonl(ctx, queued)
328
+ } catch (error) {
329
+ log?.(`archived clear queue: ${error.message}`)
330
+ return { deleted: [], kept: queued }
331
+ }
318
332
  let removed = []
319
333
  try {
320
334
  removed = await deleteSessionData(queued)
@@ -352,6 +366,7 @@ async function pruneOrphanedArchivedSessions(ctx, skip) {
352
366
  const archived = value && Array.isArray(value.archivedSessionIds)
353
367
  ? value.archivedSessionIds.filter((id) => typeof id === 'string' && id)
354
368
  : []
369
+ try { await assertSessionCleanupSupported(ctx, archived) } catch { return 0 }
355
370
  const skipped = skip instanceof Set ? skip : new Set(Array.isArray(skip) ? skip : [])
356
371
  const orphans = (await archivedIdsWithoutLogs(archived)).filter((id) => !skipped.has(id))
357
372
  if (orphans.length === 0) return 0
@@ -452,6 +467,7 @@ async function cleanupSessions(ctx, args) {
452
467
  }
453
468
  if (args.confirm !== true) throw new Error('永久删除需要 confirm: true')
454
469
  const ids = selected.map(item => item.sessionId)
470
+ if (ids.length > 0) await assertSessionCleanupSupported(ctx, ids)
455
471
  // 删之前先把这批会话的用量采进统计账本:日志一没,那部分用量就再也读不出来了。手机那个
456
472
  // 「清理已归档」按钮一直有这一刀,这条工具路以前没有 —— 走它删掉的会话,上次采集之后的
457
473
  // 那一截增量就白丢。采不上不挡删除:统计偏旧好过会话删不掉。
@@ -462,6 +478,7 @@ async function cleanupSessions(ctx, args) {
462
478
  }
463
479
  // 与移动端那条路由同一口径:进程里只排队,**日志留到宿主下次启动时删**。进程活着时
464
480
  // 删日志,宿主随时可能去开一条已经不存在的文件,那是未捕获异常(会带走整个宿主)。
481
+ if (ids.length > 0) await assertSessionCleanupStillJsonl(ctx, ids)
465
482
  queueArchivedClearIds(ids)
466
483
  rememberDeletedSessionIds(ctx, ids)
467
484
  return { action: args.action, cwd, selected: ids.length, archived: 0, deleted: ids.length, failed: 0, sessionIds: ids }
@@ -12,6 +12,7 @@ function createRoutePolicy() {
12
12
  exports.noteRouteForeign = noteRouteForeign;
13
13
  exports.isRouteForeign = isRouteForeign;
14
14
  exports.routeLatencyOf = routeLatencyOf;
15
+ exports.freshRouteLatencyOf = freshRouteLatencyOf;
15
16
  exports.routeCostOf = routeCostOf;
16
17
  exports.forgetRouteFacts = forgetRouteFacts;
17
18
  exports.orderRouteCandidates = orderRouteCandidates;
@@ -112,6 +113,11 @@ function createRoutePolicy() {
112
113
  function routeLatencyOf(url, scope = '') {
113
114
  return factsByScope.get(scope)?.latency.get(norm(url)) ?? null;
114
115
  }
116
+ function freshRouteLatencyOf(url, scope = '') {
117
+ const facts = factsByScope.get(scope);
118
+ const key = norm(url);
119
+ return facts && isFresh(facts, key) ? facts.latency.get(key) ?? null : null;
120
+ }
115
121
  function penaltyFor(facts, key) {
116
122
  return (facts.lossPenalty.get(key) ?? 1) * (facts.failurePenalty.get(key) ?? 1);
117
123
  }
@@ -0,0 +1,82 @@
1
+ // 会话统计与永久清理只认持久化服务快照和当前根的官方 SQLite 路由。
2
+ 'use strict';
3
+
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const { dshHome } = require('./paths');
7
+
8
+ const CLEANUP_UNSUPPORTED = '当前会话存储不支持永久清理(包括 SQLite):宿主未提供删除会话 API,已保留会话与归档状态。';
9
+
10
+ /** 只观察已挂载的服务;不打开句柄,以免观察本身导入旧 JSONL。 */
11
+ function sessionPersistenceOf(ctx) {
12
+ if (!ctx) return null;
13
+ if (typeof ctx.get === 'function') return ctx.get('sessionPersistence') || null;
14
+ return ctx.sessionPersistence || null;
15
+ }
16
+
17
+ async function readSessionStorage(ctx) {
18
+ const service = sessionPersistenceOf(ctx);
19
+ if (!service) return null;
20
+ const entries = await service.list();
21
+ if (!Array.isArray(entries)) throw new Error('会话持久化列表形状异常');
22
+ return { service, identity: service.identity || service, snapshots: new Map(entries.map((entry) => [entry.header.id, entry])) };
23
+ }
24
+
25
+ /** 没有服务的旧宿主也可能留下 SQLite 路由;数据库文件本身不代表当前根使用 SQLite。 */
26
+ function sqliteRoutedSessionIds() {
27
+ const directory = path.resolve(dshHome(), 'sessions', '.segments');
28
+ let names;
29
+ try { names = fs.readdirSync(directory); } catch (error) {
30
+ if (error.code === 'ENOENT') return new Set();
31
+ throw error;
32
+ }
33
+ const ids = new Set();
34
+ for (const name of names) {
35
+ if (!/^[a-f0-9]{64}\.json$/.test(name)) continue;
36
+ const route = JSON.parse(fs.readFileSync(path.join(directory, name), 'utf8'));
37
+ if (typeof route?.id !== 'string' || !route.id || route.database !== path.join(directory, 'sessions.sqlite')) {
38
+ throw new Error('会话存储路由与当前根不一致,未执行永久清理');
39
+ }
40
+ ids.add(route.id);
41
+ }
42
+ return ids;
43
+ }
44
+
45
+ function unsupportedCleanup(message = CLEANUP_UNSUPPORTED) {
46
+ return Object.assign(new Error(message), { code: 'session-cleanup-unsupported' });
47
+ }
48
+
49
+ function assertJsonlSnapshots(snapshots, sessionIds) {
50
+ // SQLite 已物化快照没有逐会话 location,但有精确 eventCount;pending JSONL 两者都没有。
51
+ if ([...snapshots.values()].some((snapshot) => snapshot.location?.kind !== 'jsonl'
52
+ && (snapshot.location || Number.isSafeInteger(snapshot.eventCount)))) throw unsupportedCleanup();
53
+ const root = path.resolve(dshHome(), 'sessions');
54
+ for (const id of sessionIds) {
55
+ const snapshot = snapshots.get(id);
56
+ if (!snapshot) continue;
57
+ if (snapshot.location?.kind !== 'jsonl' || typeof snapshot.location.path !== 'string') {
58
+ throw unsupportedCleanup('无法确认会话的 JSONL 存储位置,未执行永久清理;会话与归档状态保持不变。');
59
+ }
60
+ const relative = path.relative(root, snapshot.location.path);
61
+ if (relative.startsWith(`..${path.sep}`) || relative === '..' || path.isAbsolute(relative)) {
62
+ throw unsupportedCleanup('会话不在默认 JSONL 存储目录,未执行永久清理;会话与归档状态保持不变。');
63
+ }
64
+ }
65
+ }
66
+
67
+ /** 开始清理前确认当前实际持久化路由;共享数据库不由插件直接修改。 */
68
+ async function assertSessionCleanupSupported(ctx, sessionIds = []) {
69
+ const storage = await readSessionStorage(ctx);
70
+ if (storage) assertJsonlSnapshots(storage.snapshots, sessionIds);
71
+ else if (sqliteRoutedSessionIds().size > 0) throw unsupportedCleanup();
72
+ }
73
+
74
+ /** 补采会首次打开历史,可能刚把旧 JSONL 导入 SQLite;删除或入队前重新观察选中会话。 */
75
+ async function assertSessionCleanupStillJsonl(ctx, sessionIds) {
76
+ const service = sessionPersistenceOf(ctx);
77
+ if (!service) return assertSessionCleanupSupported(ctx, sessionIds);
78
+ const snapshots = await Promise.all(sessionIds.map((id) => service.stat(id)));
79
+ assertJsonlSnapshots(new Map(snapshots.filter(Boolean).map((snapshot) => [snapshot.header.id, snapshot])), sessionIds);
80
+ }
81
+
82
+ module.exports = { readSessionStorage, sqliteRoutedSessionIds, assertSessionCleanupSupported, assertSessionCleanupStillJsonl };