@chenacc/dsh-agentbridge 0.2.4 → 0.3.0
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 +23 -5
- package/lib/index.js +197 -15
- package/lib/tunnel.js +234 -0
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -11,6 +11,14 @@ AgentBridge 的 DSH Desktop 集成插件。在某个项目会话里执行 `/phon
|
|
|
11
11
|
|
|
12
12
|
从 0.2.0 起,桥作为依赖随插件一起安装,**DSH Desktop 启动时插件会自己在后台把桥拉起来**,所以正常情况下你什么都不用敲,重启桌面后直接 `/phone` 就行。
|
|
13
13
|
|
|
14
|
+
从 0.3.0 起,插件默认还会**自动开一条 Cloudflare 隧道**,把桥映射成一个公网 https 地址——手机用流量、在外地都能扫码打开,不必和电脑连同一个 Wi-Fi。这一步需要一个叫 `cloudflared` 的小工具(Cloudflare 官方客户端):
|
|
15
|
+
|
|
16
|
+
```powershell
|
|
17
|
+
winget install --id Cloudflare.cloudflared
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
装好重启 DSH Desktop 即可,插件会自己找到它。没装也能用,只是退回到"手机和电脑同一个 Wi-Fi"。
|
|
21
|
+
|
|
14
22
|
只有自动启动失败时(沙箱限制、端口被占、装在非常规位置)才需要手动起桥:
|
|
15
23
|
|
|
16
24
|
```powershell
|
|
@@ -51,18 +59,27 @@ pnpm add @chenacc/dsh-agentbridge@latest
|
|
|
51
59
|
|
|
52
60
|
## 使用
|
|
53
61
|
|
|
54
|
-
1.
|
|
62
|
+
1. 重启 DSH Desktop。几秒后插件会把桥拉起来,再开一条 Cloudflare 隧道,二维码里就是公网地址——手机用 Wi-Fi 或流量都能打开。
|
|
55
63
|
2. 在 DSH Desktop 里打开目标项目会话,输入 `/phone`。
|
|
56
|
-
3.
|
|
57
|
-
4.
|
|
64
|
+
3. 会话里出现一次性二维码(5 分钟有效、只能用一次)。用微信扫一扫,进入手机控制台。
|
|
65
|
+
4. 配对成功后,下次直接从手机页进入,不必再扫。
|
|
66
|
+
|
|
67
|
+
关于公网地址,有两件事值得知道:
|
|
68
|
+
|
|
69
|
+
- **地址会变。** `trycloudflare.com` 的免费域名每次隧道重建都会换一个,所以别把旧地址当书签。要保持固定地址,去 Cloudflare 建一条命名隧道,然后把 `AGENTBRIDGE_PUBLIC_ORIGIN` 设成自己的域名(这时插件就不再自己起隧道)。
|
|
70
|
+
- **它是对公网开放的。** 所以插件在开隧道时**强制打开访问密钥**,二维码里带着 `?key=…`;拿到二维码的人就能控制这台电脑,别截图外传。
|
|
58
71
|
|
|
59
72
|
## 配置
|
|
60
73
|
|
|
61
74
|
| 变量 | 默认值 | 含义 |
|
|
62
75
|
|---|---|---|
|
|
63
|
-
| `AGENTBRIDGE_ORIGIN` | `http://127.0.0.1:8787` | 插件连接的 AgentBridge
|
|
64
|
-
| `AGENTBRIDGE_DATA_DIR` | `~/.agentbridge`(自动启动时) |
|
|
76
|
+
| `AGENTBRIDGE_ORIGIN` | `http://127.0.0.1:8787` | 插件连接的 AgentBridge 地址;桥换了端口时设置它 |
|
|
77
|
+
| `AGENTBRIDGE_DATA_DIR` | `~/.agentbridge`(自动启动时) | 桥的会话、配对、密钥与日志目录,不会写进 `~/.dsh` |
|
|
65
78
|
| `AGENTBRIDGE_NO_AUTOSTART` | 未设置 | 设为 `1` 关掉"插件加载时自动起桥",只保留 `/phone` 里的手动提示 |
|
|
79
|
+
| `AGENTBRIDGE_NO_TUNNEL` | 未设置 | 设为 `1` 只用局域网,不起 Cloudflare 隧道(比如你只在家里用) |
|
|
80
|
+
| `AGENTBRIDGE_PUBLIC_ORIGIN` | 未设置 | 自己指定对外的地址(命名隧道、Tailscale、ZeroTier);设了它插件就不起隧道 |
|
|
81
|
+
| `AGENTBRIDGE_TUNNEL_URL` | 未设置 | 直接指定一个隧道域名;主要给测试和"隧道自己管"的人用 |
|
|
82
|
+
| `AGENTBRIDGE_CLOUDFLARED` | 自动查找 | `cloudflared` 不在 PATH 和常规目录时,指定它的绝对路径 |
|
|
66
83
|
|
|
67
84
|
变量要设在**真正启动 DSH Desktop 的环境里**(插件读 `process.env`),不是设在跑 bridge 的终端里。
|
|
68
85
|
|
|
@@ -82,6 +99,7 @@ pnpm remove @chenacc/dsh-agentbridge
|
|
|
82
99
|
| 版本 | 需要 |
|
|
83
100
|
|---|---|
|
|
84
101
|
| 插件 0.1.x | DSH Desktop(`@deepseek-ai/dsh-commands`、`@deepseek-ai/cordis` 由 DSH 提供)、AgentBridge `0.1.x` |
|
|
102
|
+
| 插件 0.3.x | 同上 + 可选 `cloudflared`(跨网络用) |
|
|
85
103
|
|
|
86
104
|
插件与 bridge 之间有一份集成版本号握手:bridge 侧要求的最低集成版本比插件旧时,手机端会提示"桌面端集成是旧版",升级插件即可。
|
|
87
105
|
|
package/lib/index.js
CHANGED
|
@@ -4,6 +4,7 @@ import { createRequire } from "node:module";
|
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { ensureAccessKey, findCloudflared, startQuickTunnel } from "./tunnel.js";
|
|
7
8
|
|
|
8
9
|
const name = "agentbridge-dsh-phone";
|
|
9
10
|
// `agents` is not optional: creating a conversation from the phone asks the agent
|
|
@@ -126,17 +127,26 @@ function bridgeServerEntry() {
|
|
|
126
127
|
return null;
|
|
127
128
|
}
|
|
128
129
|
|
|
129
|
-
async function
|
|
130
|
+
async function bridgeHealth(origin) {
|
|
130
131
|
try {
|
|
131
|
-
const response = await fetch(`${origin}/api/health`, { signal: AbortSignal.timeout(
|
|
132
|
-
if (!response.ok) return
|
|
132
|
+
const response = await fetch(`${origin}/api/health`, { signal: AbortSignal.timeout(1200) });
|
|
133
|
+
if (!response.ok) return null;
|
|
133
134
|
const body = await response.json().catch(() => null);
|
|
134
|
-
return body?.ok === true;
|
|
135
|
+
return body?.ok === true ? body : null;
|
|
135
136
|
} catch {
|
|
136
|
-
return
|
|
137
|
+
return null;
|
|
137
138
|
}
|
|
138
139
|
}
|
|
139
140
|
|
|
141
|
+
async function bridgeIsReady(origin) {
|
|
142
|
+
return (await bridgeHealth(origin)) !== null;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Where the plugin itself talks to the bridge. Always loopback. */
|
|
146
|
+
function localOrigin() {
|
|
147
|
+
return String(process.env.AGENTBRIDGE_ORIGIN || DEFAULT_ORIGIN).replace(/\/$/, "");
|
|
148
|
+
}
|
|
149
|
+
|
|
140
150
|
/**
|
|
141
151
|
* Whether this process may start a bridge at all.
|
|
142
152
|
*
|
|
@@ -160,7 +170,7 @@ function autoStartAllowed() {
|
|
|
160
170
|
* reported through `log`, because "nothing happened" is the hardest thing to
|
|
161
171
|
* diagnose from the outside.
|
|
162
172
|
*/
|
|
163
|
-
async function startBridge(origin, log = () => {}) {
|
|
173
|
+
async function startBridge(origin, log = () => {}, extraEnv = {}) {
|
|
164
174
|
if (await bridgeIsReady(origin)) return true;
|
|
165
175
|
if (!autoStartAllowed()) {
|
|
166
176
|
log("auto-start disabled for this process");
|
|
@@ -185,6 +195,10 @@ async function startBridge(origin, log = () => {}) {
|
|
|
185
195
|
...process.env,
|
|
186
196
|
AGENTBRIDGE_PORT: process.env.AGENTBRIDGE_PORT || port,
|
|
187
197
|
AGENTBRIDGE_DATA_DIR: dataDir,
|
|
198
|
+
// Marks this child as the plugin's own, so a later launch may stop it to pick
|
|
199
|
+
// up a new address. A bridge the user started by hand never gets this flag.
|
|
200
|
+
AGENTBRIDGE_AUTOSTART: "1",
|
|
201
|
+
...extraEnv,
|
|
188
202
|
};
|
|
189
203
|
// Under Electron `process.execPath` is DSH Desktop itself, not node: launching
|
|
190
204
|
// it with a .js path starts the app again and no server ever binds. Electron
|
|
@@ -241,6 +255,153 @@ async function startBridge(origin, log = () => {}) {
|
|
|
241
255
|
return false;
|
|
242
256
|
}
|
|
243
257
|
|
|
258
|
+
const TUNNEL_TIMEOUT_MS = 40_000;
|
|
259
|
+
const SHUTDOWN_TIMEOUT_MS = 10_000;
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Whether this process may put the bridge on the public internet.
|
|
263
|
+
*
|
|
264
|
+
* Same reasoning as `autoStartAllowed`: a test run must not create a public
|
|
265
|
+
* tunnel to the developer's machine. Both escape hatches that name an explicit
|
|
266
|
+
* address are honoured, because those are values, not side effects.
|
|
267
|
+
*/
|
|
268
|
+
function remoteAllowed() {
|
|
269
|
+
if (process.env.AGENTBRIDGE_NO_TUNNEL === "1") return false;
|
|
270
|
+
if (!autoStartAllowed()) return false;
|
|
271
|
+
if (process.env.AGENTBRIDGE_PUBLIC_ORIGIN || process.env.AGENTBRIDGE_TUNNEL_URL) return true;
|
|
272
|
+
return process.env.NODE_TEST_CONTEXT === undefined;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function bridgeDataDir() {
|
|
276
|
+
return process.env.AGENTBRIDGE_DATA_DIR || path.join(homedir(), ".agentbridge");
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* The address the QR code should carry, and the key that unlocks it.
|
|
281
|
+
*
|
|
282
|
+
* Returns null when the machine should stay on the LAN: no cloudflared, an
|
|
283
|
+
* explicit opt-out, or a tunnel that would not come up. That is not an error —
|
|
284
|
+
* same-Wi-Fi pairing still works — so the reason is logged and nothing throws.
|
|
285
|
+
*/
|
|
286
|
+
async function resolveRemoteOrigin(log) {
|
|
287
|
+
const explicit = String(process.env.AGENTBRIDGE_PUBLIC_ORIGIN ?? "").trim().replace(/\/$/, "");
|
|
288
|
+
if (explicit) return { origin: explicit, accessKey: null, how: "AGENTBRIDGE_PUBLIC_ORIGIN" };
|
|
289
|
+
|
|
290
|
+
const supplied = String(process.env.AGENTBRIDGE_TUNNEL_URL ?? "").trim().replace(/\/$/, "");
|
|
291
|
+
if (supplied) return { origin: supplied, accessKey: ensureAccessKey(bridgeDataDir()), how: "AGENTBRIDGE_TUNNEL_URL" };
|
|
292
|
+
|
|
293
|
+
const command = findCloudflared({ env: process.env, home: homedir() });
|
|
294
|
+
if (!command) {
|
|
295
|
+
log("no cloudflared found, staying on this Wi-Fi only: install it with `winget install --id Cloudflare.cloudflared`, then restart DSH Desktop");
|
|
296
|
+
return null;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const origin = localOrigin();
|
|
300
|
+
let port;
|
|
301
|
+
try {
|
|
302
|
+
port = new URL(origin).port || "8787";
|
|
303
|
+
} catch {
|
|
304
|
+
log(`cloudflare tunnel skipped: ${origin} is not a usable local origin`);
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
try {
|
|
309
|
+
const tunnel = await startQuickTunnel({
|
|
310
|
+
command,
|
|
311
|
+
origin: `http://127.0.0.1:${port}`,
|
|
312
|
+
dataDir: bridgeDataDir(),
|
|
313
|
+
log,
|
|
314
|
+
timeoutMs: TUNNEL_TIMEOUT_MS,
|
|
315
|
+
});
|
|
316
|
+
return { origin: tunnel.url, accessKey: ensureAccessKey(bridgeDataDir()), how: tunnel.reused ? "cloudflare (existing tunnel)" : "cloudflare" };
|
|
317
|
+
} catch (error) {
|
|
318
|
+
log(`cloudflare tunnel failed, staying on this Wi-Fi only: ${textFromError(error)}`);
|
|
319
|
+
return null;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Ask a bridge the plugin started to stop, so it can be respawned with a new
|
|
325
|
+
* address. A bridge the user launched themselves is never touched: the health
|
|
326
|
+
* endpoint reports whether it was autostarted, and only that flag authorises this.
|
|
327
|
+
*/
|
|
328
|
+
async function stopBridge(origin, log) {
|
|
329
|
+
let response;
|
|
330
|
+
try {
|
|
331
|
+
response = await fetch(`${origin}/api/local/shutdown`, {
|
|
332
|
+
method: "POST",
|
|
333
|
+
headers: { "content-type": "application/json" },
|
|
334
|
+
body: "{}",
|
|
335
|
+
signal: AbortSignal.timeout(5_000),
|
|
336
|
+
});
|
|
337
|
+
} catch (error) {
|
|
338
|
+
log(`could not ask the bridge to stop: ${textFromError(error)}`);
|
|
339
|
+
return false;
|
|
340
|
+
}
|
|
341
|
+
if (response.status === 409) {
|
|
342
|
+
const body = await response.json().catch(() => ({}));
|
|
343
|
+
log(`the bridge is staying on its current address: ${body?.error ?? "an Agent turn is still running"}`);
|
|
344
|
+
return false;
|
|
345
|
+
}
|
|
346
|
+
if (!response.ok) {
|
|
347
|
+
log(`the bridge refused to stop (${response.status})`);
|
|
348
|
+
return false;
|
|
349
|
+
}
|
|
350
|
+
const deadline = Date.now() + SHUTDOWN_TIMEOUT_MS;
|
|
351
|
+
while (Date.now() < deadline) {
|
|
352
|
+
await new Promise((resolve) => setTimeout(resolve, 150));
|
|
353
|
+
if (!(await bridgeIsReady(origin))) return true;
|
|
354
|
+
}
|
|
355
|
+
log("the bridge accepted the stop request but is still listening");
|
|
356
|
+
return false;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function remoteEnv(remote) {
|
|
360
|
+
return {
|
|
361
|
+
AGENTBRIDGE_PUBLIC_ORIGIN: remote.origin,
|
|
362
|
+
...(remote.accessKey ? { AGENTBRIDGE_ACCESS_KEY: remote.accessKey } : {}),
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Bring the bridge up in the best mode available, without blocking DSH startup.
|
|
368
|
+
*
|
|
369
|
+
* A bridge on loopback is useful within a second (same Wi-Fi works), while a
|
|
370
|
+
* public address needs a tunnel, which takes longer and needs cloudflared. So the
|
|
371
|
+
* local bridge always goes first and the public address is applied right after by
|
|
372
|
+
* restarting that same child — a restart the phone barely notices, because
|
|
373
|
+
* sessions, devices and the access key all live on disk.
|
|
374
|
+
*/
|
|
375
|
+
async function bringUpBridge(log) {
|
|
376
|
+
const origin = localOrigin();
|
|
377
|
+
await startBridge(origin, log);
|
|
378
|
+
if (!remoteAllowed()) return;
|
|
379
|
+
|
|
380
|
+
const health = await bridgeHealth(origin);
|
|
381
|
+
if (!health) return; // startBridge already logged why nothing came up.
|
|
382
|
+
|
|
383
|
+
const remote = await resolveRemoteOrigin(log);
|
|
384
|
+
if (!remote) return;
|
|
385
|
+
if (health.advertisedOrigin === remote.origin && (!remote.accessKey || health.accessKeyRequired === true)) {
|
|
386
|
+
log(`remote mode already active: ${remote.origin}`);
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
if (health.autostart !== true) {
|
|
390
|
+
log(
|
|
391
|
+
`the bridge already running at ${origin} was not started by this plugin, so its address cannot be changed. `
|
|
392
|
+
+ `Stop it (or restart DSH Desktop after closing it) to switch to ${remote.origin}.`,
|
|
393
|
+
);
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
if (!(await stopBridge(origin, log))) return;
|
|
397
|
+
if (await startBridge(origin, log, remoteEnv(remote))) {
|
|
398
|
+
log(`remote mode ready: ${remote.origin} (via ${remote.how})`);
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
log("the bridge did not come up with the public address, restarting it on this Wi-Fi only");
|
|
402
|
+
await startBridge(origin, log);
|
|
403
|
+
}
|
|
404
|
+
|
|
244
405
|
function clipped(value, limit) {
|
|
245
406
|
return typeof value === "string" ? value.slice(0, limit) : "";
|
|
246
407
|
}
|
|
@@ -988,6 +1149,28 @@ export class PhoneConnections {
|
|
|
988
1149
|
}
|
|
989
1150
|
}
|
|
990
1151
|
|
|
1152
|
+
/**
|
|
1153
|
+
* What the user needs to know about the address they are about to scan.
|
|
1154
|
+
*
|
|
1155
|
+
* A public tunnel URL works from any network but is reachable by anyone holding
|
|
1156
|
+
* it, so the key inside the QR is the only door. A LAN address needs no warning
|
|
1157
|
+
* beyond "be on the same Wi-Fi".
|
|
1158
|
+
*/
|
|
1159
|
+
function pairingAddressNote(url) {
|
|
1160
|
+
let host;
|
|
1161
|
+
try {
|
|
1162
|
+
host = new URL(url).hostname;
|
|
1163
|
+
} catch {
|
|
1164
|
+
return "扫码后若提示「将要访问」,点「继续访问」即可。";
|
|
1165
|
+
}
|
|
1166
|
+
const privateHost = host === "127.0.0.1"
|
|
1167
|
+
|| /^10\./.test(host)
|
|
1168
|
+
|| /^192\.168\./.test(host)
|
|
1169
|
+
|| /^172\.(1[6-9]|2\d|3[01])\./.test(host);
|
|
1170
|
+
if (privateHost) return "手机需与电脑连同一个 Wi-Fi。扫码后若提示「该地址为 IP 地址」,点「继续访问」即可。";
|
|
1171
|
+
return "这是公网地址,手机用流量也能打开;二维码里已带访问密钥,别把它转发给别人。";
|
|
1172
|
+
}
|
|
1173
|
+
|
|
991
1174
|
function apply(ctx) {
|
|
992
1175
|
const connections = new PhoneConnections(ctx);
|
|
993
1176
|
ctx.commands.register({
|
|
@@ -1010,11 +1193,11 @@ function apply(ctx) {
|
|
|
1010
1193
|
`项目:${registration.project.cwd}`,
|
|
1011
1194
|
`会话:${agent.session.id}`,
|
|
1012
1195
|
`模型:${model}`,
|
|
1013
|
-
|
|
1196
|
+
pairingAddressNote(registration.pairing.url),
|
|
1014
1197
|
].join("\n\n"),
|
|
1015
1198
|
};
|
|
1016
1199
|
} catch (error) {
|
|
1017
|
-
const origin =
|
|
1200
|
+
const origin = localOrigin();
|
|
1018
1201
|
return {
|
|
1019
1202
|
kind: "error",
|
|
1020
1203
|
text: isBridgeAbsent(error)
|
|
@@ -1027,13 +1210,12 @@ function apply(ctx) {
|
|
|
1027
1210
|
|
|
1028
1211
|
// Bring the bridge up in the background as soon as the plugin loads, so by the
|
|
1029
1212
|
// time the user types /phone the local service is already there. Deliberately
|
|
1030
|
-
// not awaited: a slow spawn
|
|
1031
|
-
// still gets the manual steps from /phone
|
|
1032
|
-
// logged instead of swallowed, because
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
(
|
|
1036
|
-
).catch((error) => ctx.logger?.warn?.(`[agentbridge-dsh-phone] auto-start crashed: ${textFromError(error)}`));
|
|
1213
|
+
// not awaited: a slow spawn — and a Cloudflare tunnel takes seconds — must never
|
|
1214
|
+
// delay desktop startup, and the user still gets the manual steps from /phone
|
|
1215
|
+
// when nothing came up. The reason is logged instead of swallowed, because
|
|
1216
|
+
// "nothing happened" is undiagnosable.
|
|
1217
|
+
void bringUpBridge((message) => ctx.logger?.warn?.(`[agentbridge-dsh-phone] ${message}`))
|
|
1218
|
+
.catch((error) => ctx.logger?.warn?.(`[agentbridge-dsh-phone] auto-start crashed: ${textFromError(error)}`));
|
|
1037
1219
|
}
|
|
1038
1220
|
|
|
1039
1221
|
export { apply, inject, name };
|
package/lib/tunnel.js
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cloudflare quick tunnel, so the phone does not have to share a Wi-Fi with the PC.
|
|
3
|
+
*
|
|
4
|
+
* A LAN-only QR code is a dead end the moment the user leaves the house, and it is
|
|
5
|
+
* also what WeChat likes least (an http URL with a bare IP address in it). A
|
|
6
|
+
* `cloudflared` quick tunnel hands back a real https hostname, which the phone can
|
|
7
|
+
* open from anywhere — at the cost of two honest caveats:
|
|
8
|
+
*
|
|
9
|
+
* - the hostname is random and changes whenever the tunnel is recreated, so a
|
|
10
|
+
* phone bookmark only lasts as long as the process keeps running;
|
|
11
|
+
* - it is a public URL, so the bridge in front of it must keep its access key on.
|
|
12
|
+
*
|
|
13
|
+
* Everything here is deliberately side-effect free until called, and every
|
|
14
|
+
* environment-dependent lookup takes an injectable dependency, because this code
|
|
15
|
+
* decides whether a public URL exists at all and that is worth testing.
|
|
16
|
+
*/
|
|
17
|
+
import { spawn } from "node:child_process";
|
|
18
|
+
import { randomBytes } from "node:crypto";
|
|
19
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
20
|
+
import os from "node:os";
|
|
21
|
+
import path from "node:path";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* A quick tunnel hostname.
|
|
25
|
+
*
|
|
26
|
+
* The negative lookahead is load-bearing: cloudflared's own failure messages quote
|
|
27
|
+
* `https://api.trycloudflare.com/tunnel`, which matches a naive pattern and would
|
|
28
|
+
* be mistaken for the tunnel the phone should open.
|
|
29
|
+
*/
|
|
30
|
+
export const TUNNEL_URL_PATTERN = /https:\/\/(?!api\.)[-a-z0-9]+\.trycloudflare\.com/;
|
|
31
|
+
|
|
32
|
+
// cloudflared writes the banner to stderr, but stdout is cheap to read too and
|
|
33
|
+
// some builds differ.
|
|
34
|
+
export function extractTunnelUrl(text) {
|
|
35
|
+
const match = TUNNEL_URL_PATTERN.exec(String(text ?? ""));
|
|
36
|
+
return match ? match[0] : null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Where `cloudflared` usually lives on Windows, best first.
|
|
41
|
+
*
|
|
42
|
+
* PATH is included because `winget` installs a shim there, and the two Program
|
|
43
|
+
* Files directories cover the MSI, which does not touch PATH from a non-elevated
|
|
44
|
+
* shell. `AGENTBRIDGE_CLOUDFLARED` wins over all of it for unusual installs.
|
|
45
|
+
*/
|
|
46
|
+
export function cloudflaredCandidates(env = process.env, home = os.homedir()) {
|
|
47
|
+
const candidates = [];
|
|
48
|
+
if (env.AGENTBRIDGE_CLOUDFLARED) candidates.push(env.AGENTBRIDGE_CLOUDFLARED);
|
|
49
|
+
for (const dir of String(env.PATH ?? "").split(path.delimiter)) {
|
|
50
|
+
if (!dir) continue;
|
|
51
|
+
candidates.push(path.join(dir, "cloudflared.exe"), path.join(dir, "cloudflared"));
|
|
52
|
+
}
|
|
53
|
+
if (env.ProgramFiles) candidates.push(path.join(env.ProgramFiles, "cloudflared", "cloudflared.exe"));
|
|
54
|
+
if (env["ProgramFiles(x86)"]) candidates.push(path.join(env["ProgramFiles(x86)"], "cloudflared", "cloudflared.exe"));
|
|
55
|
+
if (env.LOCALAPPDATA) candidates.push(path.join(env.LOCALAPPDATA, "Microsoft", "WinGet", "Links", "cloudflared.exe"));
|
|
56
|
+
// The bridge's own data directory is a last resort for a portable copy the user
|
|
57
|
+
// downloaded by hand.
|
|
58
|
+
candidates.push(path.join(home, ".agentbridge", "bin", "cloudflared.exe"));
|
|
59
|
+
return candidates;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function findCloudflared({ env = process.env, home = os.homedir(), exists = existsSync } = {}) {
|
|
63
|
+
for (const candidate of cloudflaredCandidates(env, home)) {
|
|
64
|
+
try {
|
|
65
|
+
if (exists(candidate)) return candidate;
|
|
66
|
+
} catch {
|
|
67
|
+
// An unreadable PATH entry is not worth failing the whole search.
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function accessKeyPath(dataDir) {
|
|
74
|
+
return path.join(dataDir, "access-key");
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The key that gates a publicly exposed bridge.
|
|
79
|
+
*
|
|
80
|
+
* Read before generated, so the value survives restarts: the phone already holds a
|
|
81
|
+
* cookie for it, and regenerating on every launch would silently lock the phone
|
|
82
|
+
* out of its own bridge.
|
|
83
|
+
*/
|
|
84
|
+
export function ensureAccessKey(dataDir, { readFile = readFileSync, writeFile = writeFileSync, mkdir = mkdirSync, random } = {}) {
|
|
85
|
+
const target = accessKeyPath(dataDir);
|
|
86
|
+
try {
|
|
87
|
+
const existing = String(readFile(target, "utf8")).trim();
|
|
88
|
+
if (existing.length >= 16) return existing;
|
|
89
|
+
} catch {
|
|
90
|
+
// No usable key on disk yet.
|
|
91
|
+
}
|
|
92
|
+
const key = (random ?? (() => randomBytes(24).toString("base64url")))();
|
|
93
|
+
mkdir(dataDir, { recursive: true });
|
|
94
|
+
writeFile(target, key, "utf8");
|
|
95
|
+
return key;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function tunnelStatePath(dataDir) {
|
|
99
|
+
return path.join(dataDir, "cloudflare-tunnel.json");
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function readTunnelState(dataDir, { readFile = readFileSync } = {}) {
|
|
103
|
+
try {
|
|
104
|
+
const parsed = JSON.parse(String(readFile(tunnelStatePath(dataDir), "utf8")));
|
|
105
|
+
if (!parsed || typeof parsed.url !== "string" || !Number.isInteger(parsed.pid)) return null;
|
|
106
|
+
return parsed;
|
|
107
|
+
} catch {
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function writeTunnelState(dataDir, state, { writeFile = writeFileSync, mkdir = mkdirSync, rename = renameSync } = {}) {
|
|
113
|
+
mkdir(dataDir, { recursive: true });
|
|
114
|
+
const target = tunnelStatePath(dataDir);
|
|
115
|
+
const temporary = `${target}.tmp`;
|
|
116
|
+
writeFile(temporary, JSON.stringify(state, null, 2), "utf8");
|
|
117
|
+
rename(temporary, target);
|
|
118
|
+
return state;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function isAlive(pid, { kill = process.kill.bind(process) } = {}) {
|
|
122
|
+
try {
|
|
123
|
+
kill(pid, 0);
|
|
124
|
+
return true;
|
|
125
|
+
} catch (error) {
|
|
126
|
+
// EPERM means "exists but not ours", which still counts as alive.
|
|
127
|
+
return error?.code === "EPERM";
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Start cloudflared and wait for the hostname it prints.
|
|
133
|
+
*
|
|
134
|
+
* The child is detached on purpose: the tunnel outliving DSH means the URL in an
|
|
135
|
+
* already paired phone keeps working after the desktop restarts, and it also
|
|
136
|
+
* avoids killing the tunnel whenever the Electron host decides to reload.
|
|
137
|
+
*
|
|
138
|
+
* Reuse is keyed on the state file plus a live pid plus a matching origin: a
|
|
139
|
+
* tunnel pointing at the old port would advertise a URL that resolves to a 502.
|
|
140
|
+
*/
|
|
141
|
+
export async function startQuickTunnel({
|
|
142
|
+
command,
|
|
143
|
+
origin,
|
|
144
|
+
dataDir,
|
|
145
|
+
log = () => {},
|
|
146
|
+
timeoutMs = 40_000,
|
|
147
|
+
spawnImpl = spawn,
|
|
148
|
+
fetchImpl = globalThis.fetch,
|
|
149
|
+
kill = process.kill.bind(process),
|
|
150
|
+
} = {}) {
|
|
151
|
+
if (!command) throw new Error("cloudflared was not found");
|
|
152
|
+
if (!origin) throw new Error("the tunnel needs an origin to forward to");
|
|
153
|
+
|
|
154
|
+
const previous = readTunnelState(dataDir);
|
|
155
|
+
if (previous && previous.origin === origin && isAlive(previous.pid, { kill })) {
|
|
156
|
+
const reachable = await probeTunnel(previous.url, fetchImpl);
|
|
157
|
+
if (reachable) {
|
|
158
|
+
log(`reusing the running Cloudflare tunnel at ${previous.url}`);
|
|
159
|
+
return { ...previous, reused: true };
|
|
160
|
+
}
|
|
161
|
+
log(`the recorded tunnel is no longer answering; starting a new one`);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const child = spawnImpl(command, ["tunnel", "--no-autoupdate", "--url", origin], {
|
|
165
|
+
detached: true,
|
|
166
|
+
windowsHide: true,
|
|
167
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
const state = await new Promise((resolve, reject) => {
|
|
171
|
+
let output = "";
|
|
172
|
+
let settled = false;
|
|
173
|
+
|
|
174
|
+
const finish = (error, value) => {
|
|
175
|
+
if (settled) return;
|
|
176
|
+
settled = true;
|
|
177
|
+
clearTimeout(timer);
|
|
178
|
+
if (error) reject(error);
|
|
179
|
+
else resolve(value);
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
const timer = setTimeout(() => {
|
|
183
|
+
const tail = output.trim().split(/\r?\n/).slice(-6).join(" | ");
|
|
184
|
+
try {
|
|
185
|
+
kill(child.pid, "SIGKILL");
|
|
186
|
+
} catch {
|
|
187
|
+
// Already gone.
|
|
188
|
+
}
|
|
189
|
+
finish(new Error(`cloudflared did not announce a hostname within ${Math.round(timeoutMs / 1000)}s${tail ? `: ${tail}` : ""}`));
|
|
190
|
+
}, timeoutMs);
|
|
191
|
+
timer.unref?.();
|
|
192
|
+
|
|
193
|
+
const onData = (chunk) => {
|
|
194
|
+
output += String(chunk);
|
|
195
|
+
const url = extractTunnelUrl(output);
|
|
196
|
+
if (!url) return;
|
|
197
|
+
finish(null, {
|
|
198
|
+
url,
|
|
199
|
+
pid: child.pid,
|
|
200
|
+
origin,
|
|
201
|
+
startedAt: new Date().toISOString(),
|
|
202
|
+
});
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
child.stdout?.on?.("data", onData);
|
|
206
|
+
child.stderr?.on?.("data", onData);
|
|
207
|
+
child.once?.("error", (error) => finish(new Error(`cloudflared could not start: ${error.message}`)));
|
|
208
|
+
child.once?.("exit", (code) => {
|
|
209
|
+
const tail = output.trim().split(/\r?\n/).slice(-6).join(" | ");
|
|
210
|
+
finish(new Error(`cloudflared exited with code ${code} before announcing a hostname${tail ? `: ${tail}` : ""}`));
|
|
211
|
+
});
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
// The tunnel is meant to outlive this process; the pipes are only for the banner.
|
|
215
|
+
child.unref?.();
|
|
216
|
+
child.stdout?.destroy?.();
|
|
217
|
+
child.stderr?.destroy?.();
|
|
218
|
+
return writeTunnelState(dataDir, state) && { ...state, reused: false };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Anything but a transport error means the tunnel exists.
|
|
223
|
+
*
|
|
224
|
+
* A 502 is the normal answer while the local bridge is down, and it still proves
|
|
225
|
+
* Cloudflare's edge knows this hostname.
|
|
226
|
+
*/
|
|
227
|
+
async function probeTunnel(url, fetchImpl = globalThis.fetch) {
|
|
228
|
+
try {
|
|
229
|
+
await fetchImpl(`${url}/api/health`, { signal: AbortSignal.timeout(6_000) });
|
|
230
|
+
return true;
|
|
231
|
+
} catch {
|
|
232
|
+
return false;
|
|
233
|
+
}
|
|
234
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chenacc/dsh-agentbridge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "AgentBridge for DSH Desktop: run /phone in a conversation to pair a phone console with that exact live Agent.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
},
|
|
11
11
|
"files": [
|
|
12
12
|
"lib/index.js",
|
|
13
|
+
"lib/tunnel.js",
|
|
13
14
|
"cordis.patch.yml",
|
|
14
15
|
"README.md",
|
|
15
16
|
"LICENSE"
|
|
@@ -44,7 +45,7 @@
|
|
|
44
45
|
}
|
|
45
46
|
},
|
|
46
47
|
"dependencies": {
|
|
47
|
-
"@chenacc/agentbridge": "^0.1.
|
|
48
|
+
"@chenacc/agentbridge": "^0.1.2"
|
|
48
49
|
},
|
|
49
50
|
"peerDependencies": {
|
|
50
51
|
"@deepseek-ai/dsh-commands": "^0.1.0-rc.7",
|