dsh-mobile-plugin 0.5.94 → 0.5.96
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/README.md +1 -1
- package/config/agent-presets/standard/skills/dsh-mobile-kb/SKILL.md +11 -3
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/cloudflare.md +58 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/frp.md +50 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/ipv4.md +2 -2
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/load-error-after-action.md +27 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/network-guide.md +55 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/network.md +5 -1
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/plugin-not-loaded.md +22 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/relay-server.md +48 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/relay.md +9 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/selfhost-common.md +1 -1
- package/lib/cloudflared/provision.cjs +392 -0
- package/lib/cloudflared/runner.cjs +305 -0
- package/lib/cloudflared/wiring.cjs +82 -0
- package/lib/frpc/runner.cjs +1 -1
- package/lib/impl.js +11 -1
- package/lib/mobile/history-derive.js +34 -0
- package/lib/mobile/pairing.js +4 -0
- package/lib/mobile/question-reply.js +159 -0
- package/lib/mobile/stream.js +25 -2
- package/lib/panel/index.html +47 -27
- package/lib/relay/config-store.js +9 -0
- package/lib/relay/control.js +8 -0
- package/lib/relay/core.js +6 -0
- package/lib/relay/lan-network.cjs +23 -0
- package/lib/relay/pairing-payload.cjs +2 -1
- package/lib/remote/tunnel-helper.cjs +3 -3
- package/lib/routes/control-plane.js +100 -6
- package/lib/routes/mobile-api.js +10 -2
- package/lib/shared/route-channels.cjs +1 -0
- package/lib/shared/route-order.cjs +8 -1
- package/lib/tailcat/host-process.cjs +9 -3
- package/package.json +14 -13
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
// Cloudflare 快速隧道的进程起停、banner 地址解析、崩溃退避重连与用户开关标记。
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/** 本机 cloudflared 快速隧道的进程生命周期管理。 */
|
|
5
|
+
const fs = require('node:fs');
|
|
6
|
+
const path = require('node:path');
|
|
7
|
+
const { spawn } = require('node:child_process');
|
|
8
|
+
const { dshHome } = require('../shared/paths.js');
|
|
9
|
+
|
|
10
|
+
const RESTART_DELAYS_MS = [1000, 2000, 4000, 8000, 16000];
|
|
11
|
+
// 起进程后这么久还没解析到隧道地址,就认定「连不上 Cloudflare」(国内被屏蔽/代理拦截很常见),
|
|
12
|
+
// 在状态里把原因说清,而不是一直假装「运行中」。进程不杀,交给它自己重试。
|
|
13
|
+
const CONNECT_TIMEOUT_MS = 40_000;
|
|
14
|
+
// 快速隧道分配的地址形如 https://<随机词>.trycloudflare.com,banner 里可能带装饰符或尾斜杠。
|
|
15
|
+
const TUNNEL_URL_RE = /^https:\/\/[a-z0-9-]+\.trycloudflare\.com\/?$/;
|
|
16
|
+
const ANSI_RE = /\u001b\[[0-9;]*m/g;
|
|
17
|
+
const TRIM_RE = /^[|"'<>()[\]{},;]+|[|"'<>()[\]{},;]+$/g;
|
|
18
|
+
|
|
19
|
+
function describeSpawnFailure(err, binary) {
|
|
20
|
+
const code = err && err.code ? String(err.code) : '';
|
|
21
|
+
const raw = err && err.message ? err.message : String(err || '未知错误');
|
|
22
|
+
const where = binary ? `(${binary})` : '';
|
|
23
|
+
if (code === 'UNKNOWN') {
|
|
24
|
+
return `系统拒绝运行 cloudflared${where}:多半是安全软件(如 Windows Defender)拦了这个程序,或下载到的版本与本机芯片不符。请把它加入杀毒/安全软件的信任名单,或换成与本机匹配的 cloudflared 版本。`;
|
|
25
|
+
}
|
|
26
|
+
if (code === 'ENOEXEC') return `cloudflared${where} 不是这台机器能执行的程序:文件可能已损坏,或版本/架构不对。请重新获取一份与本机匹配的 cloudflared。`;
|
|
27
|
+
if (code === 'EACCES' || code === 'EPERM') return `系统不允许运行 cloudflared${where}:权限被拒。请检查这个文件是否被禁止执行或被安全策略拦截。`;
|
|
28
|
+
if (code === 'ENOENT') return `找不到 cloudflared 可执行文件${where}:它可能已被删除或路径失效,请重新获取。`;
|
|
29
|
+
return `启动 cloudflared 失败:${raw}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 从一段(可能被装饰的)输出里取第一个合法的快速隧道地址,取不到返回空串。 */
|
|
33
|
+
function extractTunnelUrl(text) {
|
|
34
|
+
for (const raw of String(text || '').split(/\s+/)) {
|
|
35
|
+
const token = raw.replace(ANSI_RE, '').replace(TRIM_RE, '');
|
|
36
|
+
if (!token) continue;
|
|
37
|
+
if (TUNNEL_URL_RE.test(token)) return token.replace(/\/+$/, '');
|
|
38
|
+
}
|
|
39
|
+
return '';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function cloudflaredPaths(root) {
|
|
43
|
+
// 与 provision 缓存分开,避免换二进制时清掉运行期标记。
|
|
44
|
+
const dir = root || path.join(dshHome(), 'cloudflare-run');
|
|
45
|
+
return { dir, enabled: path.join(dir, 'cloudflare.enabled') };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function createCloudflaredRunner(options = {}) {
|
|
49
|
+
const paths = cloudflaredPaths(options.root);
|
|
50
|
+
// 「这台机器能不能用 cloudflared」和「二进制此刻装没装」是两回事:前者按平台判,决定面板
|
|
51
|
+
// 开关能不能点、点了会不会自动下载;后者看 binary。否则全新机器上二进制还没下来,available
|
|
52
|
+
// 恒为 false,面板把开关禁用,就永远触发不了首次下载。
|
|
53
|
+
let platformSupported = true;
|
|
54
|
+
try {
|
|
55
|
+
const provision = require('./provision.cjs');
|
|
56
|
+
if (typeof provision.platformId === 'function') platformSupported = Boolean(provision.platformId());
|
|
57
|
+
} catch { /* 取不到就按支持处理,真正 start 时再报具体原因。 */ }
|
|
58
|
+
const ensure = typeof options.ensureBin === 'function'
|
|
59
|
+
? options.ensureBin
|
|
60
|
+
: (typeof options.ensure === 'function'
|
|
61
|
+
? options.ensure
|
|
62
|
+
// 懒加载 provision:它尚未落地时不影响本模块加载,真正 start 时才取用。
|
|
63
|
+
: (opts) => require('./provision.cjs').ensureCloudflared(opts));
|
|
64
|
+
const spawnImpl = typeof options.spawnImpl === 'function' ? options.spawnImpl : spawn;
|
|
65
|
+
const portOf = typeof options.portOf === 'function' ? options.portOf : () => null;
|
|
66
|
+
const fsImpl = options.fsImpl || fs;
|
|
67
|
+
const setTimer = options.setTimerImpl || options.setTimeoutImpl || setTimeout;
|
|
68
|
+
const clearTimer = options.clearTimerImpl || options.clearTimeoutImpl || clearTimeout;
|
|
69
|
+
const sleep = typeof options.sleepImpl === 'function' ? options.sleepImpl : null;
|
|
70
|
+
// 连接超时单独一套定时器:默认走真实 setTimeout,和「崩溃重连」那套 setTimerImpl 互不影响。
|
|
71
|
+
const connectTimeoutMs = Number(options.connectTimeoutMs) > 0 ? Number(options.connectTimeoutMs) : CONNECT_TIMEOUT_MS;
|
|
72
|
+
const setConnectTimer = options.connectTimerImpl || options.setTimeoutImpl || setTimeout;
|
|
73
|
+
const clearConnectTimerImpl = options.clearConnectTimerImpl || options.clearTimeoutImpl || clearTimeout;
|
|
74
|
+
let connectTimer = null;
|
|
75
|
+
let child = null;
|
|
76
|
+
let binary = '';
|
|
77
|
+
let error = '';
|
|
78
|
+
let startedAt = 0;
|
|
79
|
+
let url = '';
|
|
80
|
+
let desired = false;
|
|
81
|
+
let generation = 0;
|
|
82
|
+
let starting = null;
|
|
83
|
+
let retryTimer = null;
|
|
84
|
+
let retries = 0;
|
|
85
|
+
let requestedLocalPort = 0;
|
|
86
|
+
let runningLocalPort = 0;
|
|
87
|
+
let waitingForPort = false;
|
|
88
|
+
let addressListener = typeof options.onAddress === 'function' ? options.onAddress : null;
|
|
89
|
+
const exists = (p) => { try { return fsImpl.existsSync(p); } catch { return false; } };
|
|
90
|
+
const localPort = () => {
|
|
91
|
+
const port = Number(portOf());
|
|
92
|
+
return Number.isInteger(port) && port >= 1024 && port <= 65535 ? port : 0;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
function writeEnabled() {
|
|
96
|
+
fsImpl.mkdirSync(paths.dir, { recursive: true });
|
|
97
|
+
fsImpl.writeFileSync(paths.enabled, '1');
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function removeEnabled() {
|
|
101
|
+
try { fsImpl.rmSync(paths.enabled, { force: true }); } catch { /* 已不存在。 */ }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function clearConnectTimer() {
|
|
105
|
+
if (connectTimer === null) return;
|
|
106
|
+
try { clearConnectTimerImpl(connectTimer); } catch { /* 已触发/失效。 */ }
|
|
107
|
+
connectTimer = null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function status() {
|
|
111
|
+
return {
|
|
112
|
+
available: Boolean(binary) || platformSupported,
|
|
113
|
+
running: Boolean(child),
|
|
114
|
+
pid: child && child.pid ? child.pid : null,
|
|
115
|
+
url: child ? url : '',
|
|
116
|
+
error,
|
|
117
|
+
startedAt,
|
|
118
|
+
starting: Boolean(starting && !child),
|
|
119
|
+
retrying: retryTimer !== null,
|
|
120
|
+
waitingForPort,
|
|
121
|
+
enabled: exists(paths.enabled),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function scheduleRestart() {
|
|
126
|
+
if (!desired || !exists(paths.enabled) || retryTimer !== null || retries >= RESTART_DELAYS_MS.length) return;
|
|
127
|
+
const token = generation;
|
|
128
|
+
retryTimer = setTimer(() => {
|
|
129
|
+
retryTimer = null;
|
|
130
|
+
if (desired && generation === token && exists(paths.enabled)) launch().catch(() => {});
|
|
131
|
+
}, RESTART_DELAYS_MS[retries++]);
|
|
132
|
+
if (retryTimer && typeof retryTimer.unref === 'function') retryTimer.unref();
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function launch() {
|
|
136
|
+
if (child) return status();
|
|
137
|
+
if (starting) { await starting; return status(); }
|
|
138
|
+
const token = ++generation;
|
|
139
|
+
const run = (async () => {
|
|
140
|
+
requestedLocalPort = localPort();
|
|
141
|
+
waitingForPort = requestedLocalPort === 0;
|
|
142
|
+
if (waitingForPort) { error = ''; return; }
|
|
143
|
+
let got;
|
|
144
|
+
try { got = await ensure({}); }
|
|
145
|
+
catch (err) { got = { ok: false, message: err && err.message ? err.message : String(err) }; }
|
|
146
|
+
if (!desired || generation !== token) return;
|
|
147
|
+
// ensureCloudflared 成功时回 { path, version, source }(没有 ok 字段),失败才抛错;
|
|
148
|
+
// 这里按「有没有 path」判成功,兼容注入的假实现回 { ok:true, path } 的写法。
|
|
149
|
+
if (!got || !got.path) {
|
|
150
|
+
error = got && got.message ? got.message : '没拿到 cloudflared 可执行文件';
|
|
151
|
+
scheduleRestart();
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
// 取二进制期间端口可能已变,启动前只取这一刻的实际监听端口。
|
|
155
|
+
const port = localPort();
|
|
156
|
+
requestedLocalPort = port;
|
|
157
|
+
waitingForPort = port === 0;
|
|
158
|
+
if (waitingForPort) { error = ''; return; }
|
|
159
|
+
binary = got.path;
|
|
160
|
+
let proc;
|
|
161
|
+
try {
|
|
162
|
+
proc = spawnImpl(binary, ['tunnel', '--url', `http://127.0.0.1:${port}`, '--no-autoupdate'], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
|
|
163
|
+
} catch (err) {
|
|
164
|
+
error = describeSpawnFailure(err, binary);
|
|
165
|
+
scheduleRestart();
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
child = proc;
|
|
169
|
+
runningLocalPort = port;
|
|
170
|
+
error = '';
|
|
171
|
+
url = '';
|
|
172
|
+
startedAt = Date.now();
|
|
173
|
+
let tail = '';
|
|
174
|
+
const isCurrent = () => desired && child === proc && generation === token;
|
|
175
|
+
// 起进程后 connectTimeoutMs 还没解析到地址:多半是连不上 Cloudflare(国内常见)。
|
|
176
|
+
// 不杀进程(它自己会重试),但把原因写进状态,面板显示「连不上」而不是假装「运行中」。
|
|
177
|
+
clearConnectTimer();
|
|
178
|
+
connectTimer = setConnectTimer(() => {
|
|
179
|
+
connectTimer = null;
|
|
180
|
+
if (isCurrent() && !url) error = '启动后还没连上 Cloudflare(可能网络无法访问 Cloudflare,如国内被屏蔽或被代理拦截),仍在后台重试';
|
|
181
|
+
}, connectTimeoutMs);
|
|
182
|
+
if (connectTimer && typeof connectTimer.unref === 'function') connectTimer.unref();
|
|
183
|
+
const consume = (chunk) => {
|
|
184
|
+
tail = (tail + String(chunk)).slice(-4000);
|
|
185
|
+
const found = extractTunnelUrl(tail);
|
|
186
|
+
if (!found || !isCurrent() || found === url) return;
|
|
187
|
+
url = found;
|
|
188
|
+
error = '';
|
|
189
|
+
clearConnectTimer();
|
|
190
|
+
if (addressListener) {
|
|
191
|
+
try {
|
|
192
|
+
const returned = addressListener(found, isCurrent);
|
|
193
|
+
if (returned && typeof returned.catch === 'function') returned.catch(() => { /* 地址写回失败不许反噬进程 */ });
|
|
194
|
+
} catch { /* 监听同步抛错同样吞掉 */ }
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
for (const stream of [proc.stdout, proc.stderr]) {
|
|
198
|
+
if (!stream || typeof stream.on !== 'function') continue;
|
|
199
|
+
if (typeof stream.setEncoding === 'function') stream.setEncoding('utf8');
|
|
200
|
+
stream.on('data', consume);
|
|
201
|
+
}
|
|
202
|
+
if (typeof proc.on === 'function') {
|
|
203
|
+
proc.on('error', (err) => { if (child === proc) error = describeSpawnFailure(err, binary); });
|
|
204
|
+
// close 时两路输出已收全,保留 cloudflared 自己给的退出原因。
|
|
205
|
+
proc.on('close', (code, signal) => {
|
|
206
|
+
if (child !== proc) return;
|
|
207
|
+
clearConnectTimer();
|
|
208
|
+
child = null;
|
|
209
|
+
runningLocalPort = 0;
|
|
210
|
+
url = '';
|
|
211
|
+
const lastLine = tail.trim() ? tail.trim().split('\n').pop() : '';
|
|
212
|
+
error = `cloudflared 已退出(code=${code}${signal ? `, ${signal}` : ''})${lastLine ? `:${lastLine}` : ''}`;
|
|
213
|
+
scheduleRestart();
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
})();
|
|
217
|
+
starting = run;
|
|
218
|
+
try { await run; }
|
|
219
|
+
finally { if (starting === run) starting = null; }
|
|
220
|
+
return status();
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async function start() {
|
|
224
|
+
if (!desired) { desired = true; retries = 0; }
|
|
225
|
+
try { writeEnabled(); } catch (err) { error = `记录启用状态失败:${err && err.message ? err.message : err}`; }
|
|
226
|
+
if (retryTimer !== null) { clearTimer(retryTimer); retryTimer = null; }
|
|
227
|
+
return launch();
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function stopProcess() {
|
|
231
|
+
generation += 1;
|
|
232
|
+
clearConnectTimer();
|
|
233
|
+
if (retryTimer !== null) clearTimer(retryTimer);
|
|
234
|
+
retryTimer = null;
|
|
235
|
+
starting = null;
|
|
236
|
+
const proc = child;
|
|
237
|
+
child = null;
|
|
238
|
+
runningLocalPort = 0;
|
|
239
|
+
url = '';
|
|
240
|
+
error = '';
|
|
241
|
+
if (proc) { try { proc.kill('SIGTERM'); } catch { /* 已退出。 */ } }
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** 监听状态变化时同步;不会越过主动停止,也不为同一个端口重启。 */
|
|
245
|
+
async function syncLocalPort() {
|
|
246
|
+
if (!desired) return status();
|
|
247
|
+
const port = localPort();
|
|
248
|
+
if (!port) { waitingForPort = !child; return status(); }
|
|
249
|
+
if (port === requestedLocalPort && !waitingForPort) return status();
|
|
250
|
+
stopProcess();
|
|
251
|
+
retries = 0;
|
|
252
|
+
return launch();
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async function stop() {
|
|
256
|
+
desired = false;
|
|
257
|
+
stopProcess();
|
|
258
|
+
requestedLocalPort = 0;
|
|
259
|
+
waitingForPort = false;
|
|
260
|
+
removeEnabled();
|
|
261
|
+
return status();
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** 宿主卸载/退出:杀进程、清地址、解绑监听,但保留 enabled 供下次启动自动恢复。 */
|
|
265
|
+
function dispose() {
|
|
266
|
+
desired = false;
|
|
267
|
+
stopProcess();
|
|
268
|
+
requestedLocalPort = 0;
|
|
269
|
+
waitingForPort = false;
|
|
270
|
+
addressListener = null;
|
|
271
|
+
return status();
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
return {
|
|
275
|
+
status, start, stop, syncLocalPort, dispose,
|
|
276
|
+
get runId() { return generation; },
|
|
277
|
+
setAddressListener(listener) {
|
|
278
|
+
addressListener = typeof listener === 'function' ? listener : null;
|
|
279
|
+
if (child && addressListener && url) {
|
|
280
|
+
const proc = child;
|
|
281
|
+
const token = generation;
|
|
282
|
+
const isCurrent = () => desired && child === proc && generation === token;
|
|
283
|
+
if (isCurrent()) {
|
|
284
|
+
try {
|
|
285
|
+
const returned = addressListener(url, isCurrent);
|
|
286
|
+
if (returned && typeof returned.catch === 'function') returned.catch(() => { /* 同上 */ });
|
|
287
|
+
} catch { /* 同上 */ }
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
},
|
|
291
|
+
async restart() { await stop(); return start(); },
|
|
292
|
+
shouldAutoStart() { return exists(paths.enabled); },
|
|
293
|
+
_paths: paths,
|
|
294
|
+
_sleep: sleep,
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
module.exports = {
|
|
299
|
+
createCloudflaredRunner,
|
|
300
|
+
extractTunnelUrl,
|
|
301
|
+
cloudflaredPaths,
|
|
302
|
+
describeSpawnFailure,
|
|
303
|
+
RESTART_DELAYS_MS,
|
|
304
|
+
CONNECT_TIMEOUT_MS,
|
|
305
|
+
};
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Cloudflare 兜底隧道接线:runner 创建、地址回报(写独立字段 cloudflareUrl)、自动启动与启停包装。
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 把 Cloudflare 兜底隧道挂进装配层:本地拉起 cloudflared 快速隧道,把拿到的 https 地址
|
|
6
|
+
* 写进**独立字段** `cloudflareUrl`(它是一条独立线路,上报时走自己的 `kind:'cf'`)。
|
|
7
|
+
*
|
|
8
|
+
* 单独一个文件是因为装配层有行数上限(`test/assembly-layer.test.cjs` 钉着)——那些上限是
|
|
9
|
+
* 「实现不许搬回装配层」。进程生命周期、banner 解析在 `runner.cjs`,二进制获取在
|
|
10
|
+
* `provision.cjs`,这里只做挂载与那几处装配动作。
|
|
11
|
+
*
|
|
12
|
+
* 写的是 `cloudflareUrl`,**绝不**写 `manualLanUrl`(用户手填的直连地址原样保留、互不覆盖),
|
|
13
|
+
* 也不写 `manualTcpUrl`(那是 frp 的 TCP 格)。停用只停 runner,不回写、不还原别的字段。
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const { createCloudflaredRunner } = require('./runner.cjs');
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @param {object} options
|
|
20
|
+
* @param {(label: string, fn: Function) => any} options.mount 装配层的兜底挂载
|
|
21
|
+
* @param {(message: string, ...rest: any[]) => void} options.warn 告警出口
|
|
22
|
+
* @param {object} options.state relay.json 那份内存状态(唯一真值)
|
|
23
|
+
* @param {{ update: (patch: object) => Promise<any> }} options.settings 配置仓(写盘并触发 applyServices)
|
|
24
|
+
* @param {() => number} options.portOf 本机实绑端口(会漂)
|
|
25
|
+
* @param {object} options.ctx 插件 ctx(只为 `ctx.effect` 与 `ctx.get`)
|
|
26
|
+
* @param {string} options.name 插件名,用于 effect 标签
|
|
27
|
+
* @returns {{ start: Function, stop: Function, status: Function, syncLocalPort: Function }}
|
|
28
|
+
*/
|
|
29
|
+
function mountCloudflare(options) {
|
|
30
|
+
const { mount, warn, state, settings, portOf, ctx, name } = options;
|
|
31
|
+
// 外壳持有 runner 时沿用(换代不重启隧道);缺省走本地。
|
|
32
|
+
let host = null;
|
|
33
|
+
try { host = typeof ctx.get === 'function' ? ctx.get('dshMobileTransportCloudflare') || null : null } catch { host = null; }
|
|
34
|
+
// 运行器创建本身万一抛错,也不能让插件加载失败:给一个「不可用但可查询原因」的降级壳。
|
|
35
|
+
let runner;
|
|
36
|
+
try {
|
|
37
|
+
runner = host && host.runner ? host.runner : createCloudflaredRunner({ portOf });
|
|
38
|
+
} catch (error) {
|
|
39
|
+
warn('Cloudflare 隧道运行器创建失败:%s', error && error.message ? error.message : error);
|
|
40
|
+
const degraded = () => ({ available: false, running: false, pid: null, url: '', error: `Cloudflare 隧道初始化失败:${error && error.message ? error.message : error}`, startedAt: 0, starting: false, retrying: false, waitingForPort: false, enabled: false });
|
|
41
|
+
return { start: async () => degraded(), stop: async () => degraded(), status: degraded, syncLocalPort: async () => degraded() };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// 控制面开关:start 幂等(runner 自己写 enabled 标记);stop 幂等(runner 删标记、停进程)。
|
|
45
|
+
// 任何一步出错都不许把异常抛回调用方(会变成面板 500 / 甚至未捕获拒绝),只记日志并把状态交回去。
|
|
46
|
+
const start = async () => {
|
|
47
|
+
try { await runner.start(); }
|
|
48
|
+
catch (error) { warn('启动 Cloudflare 隧道失败:%s', error && error.message ? error.message : error); }
|
|
49
|
+
return runner.status();
|
|
50
|
+
};
|
|
51
|
+
const stop = async () => {
|
|
52
|
+
try { await runner.stop(); }
|
|
53
|
+
catch (error) { warn('停止 Cloudflare 隧道失败:%s', error && error.message ? error.message : error); }
|
|
54
|
+
return runner.status();
|
|
55
|
+
};
|
|
56
|
+
const status = () => runner.status();
|
|
57
|
+
const syncLocalPort = () => (typeof runner.syncLocalPort === 'function' ? runner.syncLocalPort() : Promise.resolve(runner.status()));
|
|
58
|
+
|
|
59
|
+
// 地址回报:隧道拿到新 https 地址时写进独立字段 `cloudflareUrl`(不再写 `manualLanUrl`)。
|
|
60
|
+
// settings.update 会经 settings.watch → applyServices → control.sync() 自动把新地址报给总控,
|
|
61
|
+
// 总控那头从 `kind:'cf'` 这条线路上读,和用户手填的直连互不覆盖。
|
|
62
|
+
mount('cloudflare 地址', () => ctx.effect(() => {
|
|
63
|
+
if (typeof runner.setAddressListener !== 'function') return () => {};
|
|
64
|
+
runner.setAddressListener(async (address, isCurrent) => {
|
|
65
|
+
if (!isCurrent() || state.cloudflareUrl === address) return;
|
|
66
|
+
try { await settings.update({ cloudflareUrl: address }); }
|
|
67
|
+
catch (error) { warn('把 Cloudflare 地址写回状态失败:%s', error && error.message ? error.message : error); }
|
|
68
|
+
});
|
|
69
|
+
return () => runner.setAddressListener(null);
|
|
70
|
+
}, `${name}: cloudflare address`));
|
|
71
|
+
// 自动启动:上次是启用状态就再拉起;卸载时杀进程但保留 enabled 供下次恢复。
|
|
72
|
+
if (!(host && host.runner)) {
|
|
73
|
+
mount('cloudflare 隧道进程', () => ctx.effect(() => {
|
|
74
|
+
if (runner.shouldAutoStart()) Promise.resolve(runner.start()).catch((error) => warn('自动启动 Cloudflare 隧道失败:%s', error && error.message ? error.message : error));
|
|
75
|
+
return () => { void runner.dispose(); };
|
|
76
|
+
}, `${name}: cloudflare runner`));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return { start, stop, status, syncLocalPort };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
module.exports = { mountCloudflare };
|
package/lib/frpc/runner.cjs
CHANGED
|
@@ -305,7 +305,7 @@ function createFrpcRunner(options = {}) {
|
|
|
305
305
|
}
|
|
306
306
|
|
|
307
307
|
return {
|
|
308
|
-
status, start, stop, syncLocalPort, saveConfig, discoverRemoteAddress,
|
|
308
|
+
status, start, stop, syncLocalPort, saveConfig, discoverRemoteAddress, readConfig,
|
|
309
309
|
get runId() { return generation; },
|
|
310
310
|
setAddressListener(listener) {
|
|
311
311
|
addressListener = typeof listener === 'function' ? listener : null;
|
package/lib/impl.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// Cloudflare 兜底隧道:本地装配 cloudflared runner,把快速隧道地址写进独立字段 cloudflareUrl(作为新线路 kind:'cf' 上报,不再写直连格)。
|
|
1
2
|
// 身份变更同时迁移三类连接登记,主动重连独立于普通配置同步。
|
|
2
3
|
// apiProxy 兼容服务启动即提供(宿主那份晚到则自动接管),会话列表不再在启动瞬间报缺服务。
|
|
3
4
|
// 真实监听状态同步总控和穿透,固定入口约束自动换号。
|
|
@@ -47,6 +48,8 @@ const { mountTailcat } = require('./tailcat/wiring.cjs') // 直连隧道:入
|
|
|
47
48
|
const { mountP2P } = require('./p2p/wiring.cjs') // 点对点隧道:助手会话 + 落点代理(连接从隧道里进来,不必开回环门)
|
|
48
49
|
// FRP 直连:用面板导入的配置拉起本地 frpc(见 lib/frpc/runner.cjs)。
|
|
49
50
|
const { createFrpcRunner } = require('./frpc/runner.cjs')
|
|
51
|
+
// Cloudflare 兜底隧道:装配动作在 lib/cloudflared/wiring.cjs(进程在 runner.cjs)。
|
|
52
|
+
const { mountCloudflare } = require('./cloudflared/wiring.cjs')
|
|
50
53
|
const { createPreviewService } = require('./relay/preview.js')
|
|
51
54
|
const { createMuxService, createMuxAuthorizer } = require('./mobile/mux.js')
|
|
52
55
|
const { mountRemoteComputers } = require('./remote/runtime.cjs')
|
|
@@ -517,8 +520,13 @@ function apply(ctx) {
|
|
|
517
520
|
let frpHost = null
|
|
518
521
|
try { frpHost = typeof ctx.get === 'function' ? ctx.get('dshMobileTransportFrp') || null : null } catch { frpHost = null }
|
|
519
522
|
const frpRunner = frpHost && frpHost.runner ? frpHost.runner : createFrpcRunner({ portOf: advertisedLanPort })
|
|
523
|
+
const cloudflare = mountCloudflare({ mount, warn, state, settings, portOf: advertisedLanPort, ctx, name })
|
|
520
524
|
forwardingConfigured = () => frpRunner.shouldAutoStart()
|
|
521
|
-
syncNetwork = () => {
|
|
525
|
+
syncNetwork = () => {
|
|
526
|
+
control.sync()
|
|
527
|
+
void frpRunner.syncLocalPort?.().catch(warn)
|
|
528
|
+
void cloudflare.syncLocalPort?.().catch(warn)
|
|
529
|
+
}
|
|
522
530
|
syncNetwork()
|
|
523
531
|
if (frpHost && typeof frpHost.setPortProvider === 'function') frpHost.setPortProvider(advertisedLanPort)
|
|
524
532
|
mount('frpc 公网地址', () => ctx.effect(() => {
|
|
@@ -575,6 +583,8 @@ function apply(ctx) {
|
|
|
575
583
|
p2p,
|
|
576
584
|
// FRP 直连:导入配置后的启停与运行状态(见 lib/frpc/runner.cjs)。
|
|
577
585
|
frp: frpRunner,
|
|
586
|
+
// Cloudflare 兜底隧道:面板开关/状态用(见 lib/cloudflared/wiring.cjs)。
|
|
587
|
+
cloudflare,
|
|
578
588
|
getControlTargetUrl: () => control.targetUrl,
|
|
579
589
|
restartSidecar,
|
|
580
590
|
// 「手机上最近来过没有」——控制面状态里补给面板用(见 ./mobile/activity.cjs)。
|
|
@@ -48,6 +48,7 @@ const {
|
|
|
48
48
|
toolStepState,
|
|
49
49
|
} = require('./step-index.js');
|
|
50
50
|
const { deriveWorkflowRuns } = require('./workflow-runs.js');
|
|
51
|
+
const { createQuestionReplyTracker } = require('./question-reply.js');
|
|
51
52
|
|
|
52
53
|
/**
|
|
53
54
|
* 从 session.list 摘要行取会话标题(与桌面端侧栏同源,不再从 history 窗口猜):
|
|
@@ -533,6 +534,9 @@ function deriveMessages(events, sessionId, lookbackEvents) {
|
|
|
533
534
|
if (hit !== undefined) return hit;
|
|
534
535
|
}
|
|
535
536
|
const out = [];
|
|
537
|
+
// 问答累积器:`ask_user_question` 的调用先记题目、结果到达时折成一条 `question-reply` 行。
|
|
538
|
+
// 与直播(stream.js)各持一份,两边游标互不相干。
|
|
539
|
+
const questionReplies = createQuestionReplyTracker();
|
|
536
540
|
// 预扫描 tool/result 事件(同批次事件内,结果可能在调用块之前/之后出现)。
|
|
537
541
|
// `lookbackEvents` 是这一页**再往前**的一小段:倒着分页时工具结果常常落在比消息更早的位置
|
|
538
542
|
// (一轮里先跑工具、最后才写正文),只看这一页就看不出这一轮出过哪些图。
|
|
@@ -657,6 +661,20 @@ function deriveMessages(events, sessionId, lookbackEvents) {
|
|
|
657
661
|
if (typeof outputTokens === 'number' && outputTokens > 0) timing.outputTokens = outputTokens;
|
|
658
662
|
return Object.keys(timing).length > 0 ? timing : undefined;
|
|
659
663
|
};
|
|
664
|
+
/** 事件 usage → 消息模型四桶(与账本同口径;全 0 不返回,免得页脚挂「用量 0 tok」)。 */
|
|
665
|
+
const usageOfEvent = (e) => {
|
|
666
|
+
const u = e && e.data && typeof e.data.usage === 'object' ? e.data.usage : null;
|
|
667
|
+
if (!u) return undefined;
|
|
668
|
+
const pick = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
|
|
669
|
+
const usage = {
|
|
670
|
+
uncachedInputTokens: pick(u.inputTokens),
|
|
671
|
+
outputTokens: pick(u.outputTokens),
|
|
672
|
+
cacheReadTokens: pick(u.cacheReadTokens),
|
|
673
|
+
cacheWriteTokens: pick(u.cacheWriteTokens),
|
|
674
|
+
};
|
|
675
|
+
return usage.uncachedInputTokens > 0 || usage.outputTokens > 0 || usage.cacheReadTokens > 0 || usage.cacheWriteTokens > 0
|
|
676
|
+
? usage : undefined;
|
|
677
|
+
};
|
|
660
678
|
// 结构化行按 id 唯一:compactionId → 行索引(检查点行原地替换 start 行)、retryId → 行索引(原地升级)。
|
|
661
679
|
const compactionAt = new Map();
|
|
662
680
|
// 一轮里的压缩尝试行(turn → 行索引表):同一轮的多次尝试共用一行,见 pendingCompactionAt。
|
|
@@ -705,6 +723,9 @@ function deriveMessages(events, sessionId, lookbackEvents) {
|
|
|
705
723
|
return;
|
|
706
724
|
}
|
|
707
725
|
if (raw.type !== 'tool-call') return;
|
|
726
|
+
// `ask_user_question` 不进球过程:它答完会落成一条「问 + 答」气泡(见 question-reply.js),
|
|
727
|
+
// 再留一行空摘要的工具步骤只是同一次提问被画两遍。
|
|
728
|
+
if (raw.name === 'ask_user_question') return;
|
|
708
729
|
const callId = raw.id != null ? String(raw.id) : undefined;
|
|
709
730
|
const result = callId ? toolResults.get(callId) : undefined;
|
|
710
731
|
const rawArgs = typeof raw.arguments === 'string'
|
|
@@ -799,6 +820,8 @@ function deriveMessages(events, sessionId, lookbackEvents) {
|
|
|
799
820
|
if (item.role !== 'user') {
|
|
800
821
|
const timing = timingOf(e);
|
|
801
822
|
if (timing) item.timing = timing;
|
|
823
|
+
const usage = usageOfEvent(e);
|
|
824
|
+
if (usage) item.usage = usage;
|
|
802
825
|
}
|
|
803
826
|
out.push(item);
|
|
804
827
|
// 这一轮的过程清单挂在**开启这一轮的那条消息**上:App 的头条行按它派生。
|
|
@@ -848,6 +871,17 @@ function deriveMessages(events, sessionId, lookbackEvents) {
|
|
|
848
871
|
const e = entry.event || entry;
|
|
849
872
|
const seq = e.seq;
|
|
850
873
|
const time = e.time;
|
|
874
|
+
// 问答派生:`ask_user_question` 的调用先记题目、结果到达时吐一条 `question-reply` 行。
|
|
875
|
+
// `tool/call` / `tool/result` 其余情况此前整条忽略,`assistant/message` 还要继续走下面的
|
|
876
|
+
// 消息折叠,所以只有前两种吃 `continue`。
|
|
877
|
+
if (e.type === 'tool/call' || e.type === 'tool/result') {
|
|
878
|
+
const reply = questionReplies.note(e);
|
|
879
|
+
if (reply) out.push(reply);
|
|
880
|
+
continue;
|
|
881
|
+
}
|
|
882
|
+
if (e.type === 'assistant/message' && e.data && e.data.message) {
|
|
883
|
+
questionReplies.note(e);
|
|
884
|
+
}
|
|
851
885
|
// 工作流那四类事件不在这里就地折:攒起来整窗看(见 `workflowEntries`)。
|
|
852
886
|
if (typeof e.type === 'string' && e.type.startsWith('tool-workflow/')) {
|
|
853
887
|
workflowEntries.push(entry.event ? entry : { event: e });
|
package/lib/mobile/pairing.js
CHANGED
|
@@ -355,6 +355,10 @@ function createPairHandler(deps) {
|
|
|
355
355
|
// 没有二维码,这是它拿到这条 TCP 地址的唯一机会)。**始终带这一格**(可为空串),
|
|
356
356
|
// 与 `/connection-info` 同一口径:老手机读到空值按「没有」处理,新手机据此知道宿主报过。
|
|
357
357
|
tcpUrl: tcpDirectTarget(state.manualTcpUrl),
|
|
358
|
+
// 「Cloudflare 兜底隧道」地址:**独立一格**,不塞进 directUrl(它是新线路,不是直连的
|
|
359
|
+
// 变体)。始终带这一格(可为空串),与 `/connection-info` 同一口径:老手机读到空值按
|
|
360
|
+
// 「没有」处理,新手机据此知道宿主报过这条线路。
|
|
361
|
+
cloudflareUrl: typeof state.cloudflareUrl === 'string' ? state.cloudflareUrl : '',
|
|
358
362
|
};
|
|
359
363
|
|
|
360
364
|
// 新协议的回包必须加密:里面有 token / cookie / deviceCredential,明文回包等于让
|