dsh-mobile-plugin 0.5.90 → 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.
- package/config/agent-presets/standard/skills/dsh-mobile-kb/SKILL.md +14 -3
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/ipv4.md +38 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/ipv6.md +36 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/selfhost-common.md +44 -0
- package/docs/extension-authoring.md +4 -4
- package/extension-registry/index.json +5 -1
- package/host.js +7 -15
- package/lib/client.js +20 -12
- package/lib/host-compat.cjs +4 -1
- package/lib/host-preset-patches.cjs +40 -0
- package/lib/impl.js +30 -22
- package/lib/index.js +3 -0
- package/lib/mobile/agent-presets.js +12 -0
- package/lib/mobile/answer-sources.js +3 -2
- package/lib/mobile/archive-clean.js +5 -0
- package/lib/mobile/history-derive.js +3 -7
- package/lib/mobile/host-bridge/shims.js +20 -3
- package/lib/mobile/host-bridge.js +30 -1
- package/lib/mobile/live-steps.js +4 -3
- package/lib/mobile/plugin-self.js +4 -0
- package/lib/mobile/relay-control.js +63 -0
- package/lib/mobile/session-cache.js +12 -1
- package/lib/mobile/session-models.js +1 -1
- package/lib/mobile/session-presets.js +5 -2
- package/lib/mobile/session-send.js +0 -4
- package/lib/mobile/session-step.js +3 -2
- package/lib/mobile/stats-collect.cjs +26 -8
- package/lib/mobile/step-index.js +4 -3
- package/lib/mobile/subagents.js +0 -5
- package/lib/mobile/tool-result-state.js +12 -0
- package/lib/panel/index.html +27 -28
- package/lib/relay/lan-discovery.cjs +18 -3
- package/lib/relay/lan-proxy.js +22 -2
- package/lib/routes/control-plane.js +13 -2
- package/lib/session-cleanup.cjs +17 -0
- package/lib/shared/session-storage.cjs +82 -0
- package/lib/shell/first-install.js +102 -0
- package/lib/shell/updater.js +6 -5
- package/lib/sidecar-facade-worker.cjs +2 -0
- package/lib/tailcat/wiring.cjs +2 -2
- package/package.json +2 -2
- package/lib/mobile/ai-recipient.cjs +0 -61
|
@@ -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
|
-
|
|
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
|
}
|
package/lib/relay/lan-proxy.js
CHANGED
|
@@ -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
|
|
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
|
|
532
|
+
channelFor(req),
|
|
513
533
|
`${formatHost(upstreamHost)}:${upstreamPort}`,
|
|
514
534
|
);
|
|
515
535
|
// 上游要认得这条请求:新 T1 记录没有存下来的宿主令牌,就把请求里出示的那一枚
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 配对二维码在隧道窗口就绪后取当前状态,渲染完成前复核票据与身份。
|
|
1
2
|
// 网络动作区分配置受理与真实连接,主动重连使用独立动作并保留探测总期限。
|
|
2
3
|
// 注册本机控制面,并在吊销回执完成后关闭本实例在途连接。
|
|
3
4
|
// 本机面板读取上报目的地,FRP 仅在明确保存后启动,停用清除直连目标。
|
|
@@ -794,14 +795,20 @@ function registerControlPlaneRoutes(deps) {
|
|
|
794
795
|
const previewUrl = preview && /^https?:\/\/[^\s]+$/i.test(preview.trim())
|
|
795
796
|
? preview.trim().replace(/\/+$/, '')
|
|
796
797
|
: ''
|
|
797
|
-
const source = previewUrl ? { ...state, relayUrl: previewUrl, relayUrls: [previewUrl] } : state
|
|
798
|
-
const { payload } = pairingPayload(source, lanPortInUse())
|
|
799
798
|
// 直连隧道:这一个是「不配中转也能连」的那条路。窗口是现开的一次性小节点(两分钟、
|
|
800
799
|
// 只放行当场那把钥匙),开不出来就照旧只给局域网与中转——所以它永远只是加一条路,
|
|
801
800
|
// 不会让原来那套配不上。
|
|
802
801
|
const tailcat = deps.tailcat && typeof deps.tailcat.openPairingWindow === 'function'
|
|
803
802
|
? await deps.tailcat.openPairingWindow(120).catch(() => null)
|
|
804
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())
|
|
805
812
|
if (tailcat) {
|
|
806
813
|
payload.tailcat = {
|
|
807
814
|
version: 1,
|
|
@@ -847,6 +854,10 @@ function registerControlPlaneRoutes(deps) {
|
|
|
847
854
|
margin: 4,
|
|
848
855
|
width: 1024,
|
|
849
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
|
+
}
|
|
850
861
|
sendJson(res, 200, {
|
|
851
862
|
ok: true,
|
|
852
863
|
name: payload.name,
|
package/lib/session-cleanup.cjs
CHANGED
|
@@ -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 }
|
|
@@ -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 };
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「第一次把这个插件装进一台正在跑的 DSH」的判定。
|
|
3
|
+
*
|
|
4
|
+
* 为什么要单独记一笔:DSH 会把新装的 bundle 热加载起来(HMR),于是插件一装上、进程没重启
|
|
5
|
+
* 也能跑、手机也连得上 —— 但这一代没走过 DSH 的启动装载,桌面端那半(侧栏 / 设置页的外壳
|
|
6
|
+
* 资源)还没真正就位。装完让人**完整重启一次 DSH** 才是干净的收尾,手机端据此给一句明确
|
|
7
|
+
* 提示(见 `plugin/self` 的 `firstInstallPendingRestart`)。
|
|
8
|
+
*
|
|
9
|
+
* 判据只有两条,都取自现场、不猜:
|
|
10
|
+
* · 这个 profile 里**从没跑过**这个插件(`$DSH_HOME` 里没有落过标记);
|
|
11
|
+
* · 盘上这份的落盘时间**晚于 DSH 进程启动** —— 说明它是进程起来之后才装进来的(HMR),
|
|
12
|
+
* 而不是进程启动时就加载好的那一份。
|
|
13
|
+
*
|
|
14
|
+
* 第一次跑过就在 `$DSH_HOME` 里落一个标记:下次(重启之后)不再判成首次。装的时候 DSH 本来
|
|
15
|
+
* 就关着(下次启动会自然加载)、或已经重启过,都不会命中,也就不会冒一个假的重启要求。
|
|
16
|
+
* 取不到落盘时间(源码挂载 / 无头部署)一律按「不提示」处理 —— 宁可少提醒,不给假提醒。
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import fs from 'node:fs'
|
|
20
|
+
import path from 'node:path'
|
|
21
|
+
import { dshHome } from '../shared/paths.js'
|
|
22
|
+
import { installedPackageDir } from './manager.js'
|
|
23
|
+
|
|
24
|
+
/** 首次跑过的标记文件(落在 `$DSH_HOME`)。多个 profile 共用一个 DSH_HOME 时按 profile 分开。 */
|
|
25
|
+
const MARKER = 'mobile-plugin-first-run.json'
|
|
26
|
+
|
|
27
|
+
/** 标记文件名:带上 profile 名,免得多套 profile 共用一个 DSH_HOME 时互相顶掉。 */
|
|
28
|
+
function markerName() {
|
|
29
|
+
const profile = String(process.env.DSH_PROFILE || '').trim()
|
|
30
|
+
return profile ? `mobile-plugin-first-run.${profile.replace(/[^\w.-]/g, '_')}.json` : MARKER
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 纯判定:只回答「要不要提示重启一次」。
|
|
35
|
+
*
|
|
36
|
+
* 拆出来是为了能在裸 Node 里被守卫直接钉住 —— 真实落盘时间与进程启动时间都在调用方取。
|
|
37
|
+
*
|
|
38
|
+
* @param {{seenBefore: boolean, installedBirthMs: number|null, processStartMs: number|null}} input
|
|
39
|
+
* @returns {boolean}
|
|
40
|
+
*/
|
|
41
|
+
export function decideNeedsRestart({ seenBefore, installedBirthMs, processStartMs }) {
|
|
42
|
+
if (seenBefore) return false
|
|
43
|
+
if (!Number.isFinite(installedBirthMs) || !Number.isFinite(processStartMs)) return false
|
|
44
|
+
return installedBirthMs > processStartMs
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 本进程大概是什么时候起的:拿不到更准的口径,用它比落盘时间已经够。 */
|
|
48
|
+
function processStartMs() {
|
|
49
|
+
const up = typeof process.uptime === 'function' ? process.uptime() : 0
|
|
50
|
+
return Date.now() - (Number.isFinite(up) ? up : 0) * 1000
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 盘上这份插件目录的创建时刻;没有 birthtime 的平台退回 ctime。取不到回 null。 */
|
|
54
|
+
function installedBirthMs(dir) {
|
|
55
|
+
try {
|
|
56
|
+
const stat = fs.statSync(dir)
|
|
57
|
+
if (Number.isFinite(stat.birthtimeMs) && stat.birthtimeMs > 0) return stat.birthtimeMs
|
|
58
|
+
return Number.isFinite(stat.ctimeMs) && stat.ctimeMs > 0 ? stat.ctimeMs : null
|
|
59
|
+
} catch {
|
|
60
|
+
return null
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 本进程里只判一次:装载 / 换代都可能反复读状态,别让标记写一半、读一半。 */
|
|
65
|
+
let decided = null
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 这次装载是不是「第一次装、而且装的时候 DSH 正开着(还没重启过)」。
|
|
69
|
+
*
|
|
70
|
+
* 结果按进程缓存;顺带把「跑过一次」记进 `$DSH_HOME`,让重启后不再算首次。
|
|
71
|
+
*
|
|
72
|
+
* @returns {boolean}
|
|
73
|
+
*/
|
|
74
|
+
export function firstInstallNeedsRestart() {
|
|
75
|
+
if (decided !== null) return decided
|
|
76
|
+
const home = dshHome()
|
|
77
|
+
const marker = path.join(home, markerName())
|
|
78
|
+
let seenBefore = false
|
|
79
|
+
try {
|
|
80
|
+
seenBefore = fs.existsSync(marker)
|
|
81
|
+
} catch {
|
|
82
|
+
seenBefore = false
|
|
83
|
+
}
|
|
84
|
+
const dir = installedPackageDir()
|
|
85
|
+
const needs = decideNeedsRestart({
|
|
86
|
+
seenBefore,
|
|
87
|
+
installedBirthMs: dir ? installedBirthMs(dir) : null,
|
|
88
|
+
processStartMs: processStartMs(),
|
|
89
|
+
})
|
|
90
|
+
// 记下「跑过一次」。写不进去不挡任何事:顶多下次重启后再判一次(那时落盘时间已经早于进程
|
|
91
|
+
// 启动,结果仍是 false),不会误报。
|
|
92
|
+
if (!seenBefore) {
|
|
93
|
+
try {
|
|
94
|
+
fs.mkdirSync(home, { recursive: true })
|
|
95
|
+
fs.writeFileSync(marker, JSON.stringify({ seenAt: new Date().toISOString(), needsRestart: needs }))
|
|
96
|
+
} catch {
|
|
97
|
+
/* 记不下来就算了 */
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
decided = needs
|
|
101
|
+
return decided
|
|
102
|
+
}
|
package/lib/shell/updater.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** 更新账本保留安装恢复结果,常驻 Tailcat 代码变化提示重新载入外壳。 */
|
|
2
2
|
/**
|
|
3
3
|
* 更新编排:查与装都归实现自己,装完就地换代(不重启 DSH)。
|
|
4
4
|
*
|
|
@@ -13,8 +13,8 @@
|
|
|
13
13
|
* 兜底那条路不下载、不解包、不校验、不写 profile,只回答「有没有新版、装完了没、盘上是什么
|
|
14
14
|
* 版本」。
|
|
15
15
|
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
16
|
+
* 外壳指纹包含入口、外壳目录和外壳持有的 Tailcat 静态依赖,由换代守卫逐文件钉住;
|
|
17
|
+
* 常驻模块必须同步进来,否则换代沿用旧代码时面板收不到重启提示。
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
20
|
import fs from 'node:fs'
|
|
@@ -62,7 +62,7 @@ function installedPackageDirSafe() {
|
|
|
62
62
|
}
|
|
63
63
|
|
|
64
64
|
/**
|
|
65
|
-
*
|
|
65
|
+
* 外壳及其常驻 Tailcat 依赖的内容指纹;传输门面跨代存活,依赖也要重载才会更换。
|
|
66
66
|
*
|
|
67
67
|
* **外壳换不掉**:它在进程启动时被 Node 缓存,改它必须重启 DSH —— 而重启是被明令禁止的。
|
|
68
68
|
* 所以「新版本连外壳一起改了」这件事**不会**在这次更新里生效:实现换成新的了,装载它的
|
|
@@ -73,7 +73,8 @@ function installedPackageDirSafe() {
|
|
|
73
73
|
*/
|
|
74
74
|
export function shellFingerprint(pkgDir) {
|
|
75
75
|
if (!pkgDir) return null
|
|
76
|
-
const files = ['lib/index.js', 'lib/shell/runtime.js', 'lib/shell/manager.js', 'lib/shell/updater.js', 'lib/shell/device-ota.js', 'lib/shell/ota-package.js', 'lib/shell/ota-signing.js', 'lib/shell/ota-public-key.js', 'lib/shell/half-route.js', 'lib/shell/half-view.js', 'lib/shell/self-check-after-swap.js', 'lib/shell/transport-host.js'
|
|
76
|
+
const files = ['lib/index.js', 'lib/shell/runtime.js', 'lib/shell/manager.js', 'lib/shell/updater.js', 'lib/shell/device-ota.js', 'lib/shell/ota-package.js', 'lib/shell/ota-signing.js', 'lib/shell/ota-public-key.js', 'lib/shell/half-route.js', 'lib/shell/half-view.js', 'lib/shell/self-check-after-swap.js', 'lib/shell/transport-host.js', 'lib/shell/first-install.js',
|
|
77
|
+
'lib/tailcat/wiring.cjs', 'lib/tailcat/session.cjs', 'lib/tailcat/ingress.cjs', 'lib/tailcat/host-process.cjs', 'lib/relay/tunnel-forwarder.cjs', 'lib/shared/via-header.js']
|
|
77
78
|
const hash = createHash('sha256')
|
|
78
79
|
let seen = 0
|
|
79
80
|
for (const rel of files) {
|
|
@@ -744,6 +744,8 @@ async function startLan() {
|
|
|
744
744
|
pairingTier: config.pairingTier || 'full',
|
|
745
745
|
upstreamPort: config.upstreamPort,
|
|
746
746
|
upstreamHost: config.upstreamHost || '127.0.0.1',
|
|
747
|
+
// 手填直连地址:交给局域网代理按 Host 区分「外网穿透」与「局域网」,别再标成局域网。
|
|
748
|
+
manualLanUrl: config.manualLanUrl || '',
|
|
747
749
|
readSnapshot: snapshotRead,
|
|
748
750
|
onLog: (...args) => process.stderr.write(`[dsh-ai-hub sidecar] ${args.join(' ')}\n`),
|
|
749
751
|
// 配对成功之后换码 + 换票据:走宿主的控制面(那是唯一能写状态文件的地方)。
|
package/lib/tailcat/wiring.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//
|
|
1
|
+
// 装配门面保留真实启动错误,正常等待与默认关闭不产生故障。
|
|
2
2
|
'use strict';
|
|
3
3
|
// 隧道始终走独立的带来源标记入口,不依赖局域网监听。
|
|
4
4
|
// 落点代理转给宿主时跟随宿主实际绑定地址(见 relay/tunnel-forwarder.cjs)。
|
|
@@ -92,7 +92,7 @@ function mountTailcat(options) {
|
|
|
92
92
|
const base = session && !startupError
|
|
93
93
|
? session.status()
|
|
94
94
|
: { available: Boolean(ingress && forwarder && !startupError), enabled: (readState() || {}).tailcatEnabled === true,
|
|
95
|
-
ready: false, address: '', paired: 0, error: startupError
|
|
95
|
+
ready: false, address: '', paired: 0, error: startupError };
|
|
96
96
|
return { ...base, targetPort: resolvedTargetPort() };
|
|
97
97
|
},
|
|
98
98
|
openPairingWindow: ttl => (session ? session.openPairingWindow(ttl) : Promise.resolve(null)),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-mobile-plugin",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.91",
|
|
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",
|
|
@@ -75,7 +75,7 @@
|
|
|
75
75
|
"dependencies": {
|
|
76
76
|
"bonjour-service": "1.4.4",
|
|
77
77
|
"qrcode": "1.5.4",
|
|
78
|
-
"ws": "8.
|
|
78
|
+
"ws": "8.23.0"
|
|
79
79
|
},
|
|
80
80
|
"optionalDependencies": {
|
|
81
81
|
"dsh-mobile-shell-darwin-arm64": "0.1.2",
|
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
/** 已知自建端点在接入 prompt 前核对当前模型与配置;不读取凭据,不承诺队列未来每步的路由。 */
|
|
2
|
-
'use strict';
|
|
3
|
-
const { unwrap } = require('./envelope.js');
|
|
4
|
-
|
|
5
|
-
function publicEndpoint(value) {
|
|
6
|
-
try {
|
|
7
|
-
const url = new URL(typeof value === 'string' ? value : '');
|
|
8
|
-
if (url.protocol !== 'https:' && url.protocol !== 'http:') return '';
|
|
9
|
-
return `${url.protocol}//${url.host}${url.pathname.replace(/\/+$/, '')}`;
|
|
10
|
-
} catch { return ''; }
|
|
11
|
-
}
|
|
12
|
-
function refusal(code) {
|
|
13
|
-
return { code, message: code === 'ai-recipient-changed'
|
|
14
|
-
? '模型接收方已改变,请回到手机重新确认后发送。'
|
|
15
|
-
: '这台电脑无法核实已确认的模型接收方,请更新插件或重新确认当前路由。' };
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/** 缺省字段保留逐消息授权电脑当前路由的旧路径;显式字段不允许悄悄降级。 */
|
|
19
|
-
async function expectedAiRecipientError(ctx, { sessionId, expected, selection, child = false }) {
|
|
20
|
-
if (expected === undefined) return null;
|
|
21
|
-
if (!expected || typeof expected !== 'object' || typeof expected.provider !== 'string'
|
|
22
|
-
|| !expected.provider.trim() || !publicEndpoint(expected.endpoint)) {
|
|
23
|
-
return { code: 'bad-request', message: 'expectedAiRecipient 需要 { provider, endpoint }。' };
|
|
24
|
-
}
|
|
25
|
-
const provider = expected.provider.trim();
|
|
26
|
-
const endpoint = publicEndpoint(expected.endpoint);
|
|
27
|
-
if (selection && selection.provider !== provider) return refusal('ai-recipient-changed');
|
|
28
|
-
try {
|
|
29
|
-
const llm = ctx.get && ctx.get('llm');
|
|
30
|
-
if (!llm || typeof llm.resolveCallConfig !== 'function') return refusal('ai-recipient-unverifiable');
|
|
31
|
-
const agents = ctx.get && ctx.get('agents');
|
|
32
|
-
let agent = agents && typeof agents.get === 'function' ? agents.get(sessionId) : null;
|
|
33
|
-
if (!agent && !child) {
|
|
34
|
-
const controller = ctx.get && ctx.get('sessionController');
|
|
35
|
-
if (controller && typeof controller.resolveAgent === 'function') {
|
|
36
|
-
const resolved = await controller.resolveAgent(sessionId);
|
|
37
|
-
if (resolved && !resolved.error) agent = resolved.agent;
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
const actual = agent && agent.model && typeof agent.model.current === 'function' ? agent.model.current() : null;
|
|
41
|
-
if (!actual || !actual.provider || !actual.model) return refusal('ai-recipient-unverifiable');
|
|
42
|
-
if (actual.provider !== provider) return refusal('ai-recipient-changed');
|
|
43
|
-
// 这是宿主当前模型配置校验,不把客户端声称的 route 当成实际 route。
|
|
44
|
-
const resolved = await llm.resolveCallConfig(actual);
|
|
45
|
-
if (!resolved || resolved.provider !== actual.provider || resolved.model !== actual.model) return refusal('ai-recipient-unverifiable');
|
|
46
|
-
const settings = unwrap(await ctx.apiProxy.settings.describe({ rpcId: 'mobile', method: 'settings.describe', payload: {} }));
|
|
47
|
-
if (settings.error) return refusal('ai-recipient-unverifiable');
|
|
48
|
-
const rows = Array.isArray(settings.value) ? settings.value : settings.value && settings.value.namespaces;
|
|
49
|
-
const namespace = Array.isArray(rows) ? rows.find((row) => row && row.ns === 'llm-pi-ai') : null;
|
|
50
|
-
const profiles = namespace && namespace.value && namespace.value.providers;
|
|
51
|
-
const profile = profiles && Object.hasOwn(profiles, provider) ? profiles[provider] : null;
|
|
52
|
-
// llm-pi-ai 的显式 baseURL 覆盖全部模型端点;无显式值时内置模型可能各用自己的端点。
|
|
53
|
-
const actualEndpoint = publicEndpoint(profile && profile.baseURL);
|
|
54
|
-
if (!actualEndpoint) return refusal('ai-recipient-unverifiable');
|
|
55
|
-
if (actualEndpoint !== endpoint) return refusal('ai-recipient-changed');
|
|
56
|
-
return null;
|
|
57
|
-
} catch {
|
|
58
|
-
return refusal('ai-recipient-unverifiable');
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
module.exports = { publicEndpoint, expectedAiRecipientError };
|