@chenacc/dsh-agentbridge 0.3.1 → 0.3.3

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 CHANGED
@@ -11,13 +11,17 @@ 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 官方客户端):
14
+ 从 0.3.0 起,插件默认还会**自动开一条 Cloudflare 隧道**,把桥映射成一个公网 https 地址——手机用流量、在外地都能扫码打开,不必和电脑连同一个 Wi-Fi。
15
+
16
+ 这一步需要一个叫 `cloudflared` 的小工具(Cloudflare 官方客户端)。**你不用管它**:插件会先在本机找,找不到就自己从 Cloudflare 官方的 GitHub Releases 下载一份到 `~\.agentbridge\bin\cloudflared.exe`(约 55 MB,只下一次,不用管理员权限,删掉那个文件夹就等于卸载)。下载完还会跑一次 `cloudflared --version` 验证,验不过的文件不会留在磁盘上。
17
+
18
+ 想自己装也行,插件优先用系统里已有的那份:
15
19
 
16
20
  ```powershell
17
21
  winget install --id Cloudflare.cloudflared
18
22
  ```
19
23
 
20
- 装好重启 DSH Desktop 即可,插件会自己找到它。没装也能用,只是退回到"手机和电脑同一个 Wi-Fi"。
24
+ 下载不到(断网、公司代理拦着)也能用,只是退回到"手机和电脑同一个 Wi-Fi",日志里会说明原因。
21
25
 
22
26
  只有自动启动失败时(沙箱限制、端口被占、装在非常规位置)才需要手动起桥:
23
27
 
@@ -79,7 +83,9 @@ pnpm add @chenacc/dsh-agentbridge@latest
79
83
  | `AGENTBRIDGE_NO_TUNNEL` | 未设置 | 设为 `1` 只用局域网,不起 Cloudflare 隧道(比如你只在家里用) |
80
84
  | `AGENTBRIDGE_PUBLIC_ORIGIN` | 未设置 | 自己指定对外的地址(命名隧道、Tailscale、ZeroTier);设了它插件就不起隧道 |
81
85
  | `AGENTBRIDGE_TUNNEL_URL` | 未设置 | 直接指定一个隧道域名;主要给测试和"隧道自己管"的人用 |
82
- | `AGENTBRIDGE_CLOUDFLARED` | 自动查找 | `cloudflared` 不在 PATH 和常规目录时,指定它的绝对路径 |
86
+ | `AGENTBRIDGE_CLOUDFLARED` | 自动查找 | 用你自己那份 `cloudflared`;设了它插件既不搜索也不下载 |
87
+ | `AGENTBRIDGE_NO_DOWNLOAD` | 未设置 | 设为 `1` 禁止插件自动下载 `cloudflared`(会退回局域网) |
88
+ | `AGENTBRIDGE_CLOUDFLARED_URL` | 官方 GitHub Releases | 换一个下载源(内网镜像之类);下载后照样要过 `--version` 校验 |
83
89
 
84
90
  变量要设在**真正启动 DSH Desktop 的环境里**(插件读 `process.env`),不是设在跑 bridge 的终端里。
85
91
 
@@ -99,7 +105,7 @@ pnpm remove @chenacc/dsh-agentbridge
99
105
  | 版本 | 需要 |
100
106
  |---|---|
101
107
  | 插件 0.1.x | DSH Desktop(`@deepseek-ai/dsh-commands`、`@deepseek-ai/cordis` 由 DSH 提供)、AgentBridge `0.1.x` |
102
- | 插件 0.3.x | 同上 + 可选 `cloudflared`(跨网络用) |
108
+ | 插件 0.3.x | 同上 + `cloudflared`(跨网络用;缺了会自动下载) |
103
109
 
104
110
  插件与 bridge 之间有一份集成版本号握手:bridge 侧要求的最低集成版本比插件旧时,手机端会提示"桌面端集成是旧版",升级插件即可。
105
111
 
package/lib/index.js CHANGED
@@ -4,7 +4,27 @@ 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, ensureAutostartToken, findCloudflared, readAutostartToken, startQuickTunnel } from "./tunnel.js";
7
+
8
+ /**
9
+ * The tunnel machinery lives in the bridge package, because the CLI needs exactly
10
+ * the same thing — `agentbridge phone` has to publish a public address too.
11
+ *
12
+ * Loaded lazily rather than at module scope: inside this repository the plugin
13
+ * sits in the bridge package's own tree with no `node_modules` entry to resolve,
14
+ * and a top-level await there would make the module impossible to even import
15
+ * (which is what the release check does). The published package always carries
16
+ * the dependency, so the relative fallback only runs for development and tests.
17
+ */
18
+ let tunnelModule = null;
19
+ async function tunnel() {
20
+ if (tunnelModule) return tunnelModule;
21
+ try {
22
+ tunnelModule = await import("@chenacc/agentbridge/tunnel");
23
+ } catch {
24
+ tunnelModule = await import("../../../src/tunnel.js");
25
+ }
26
+ return tunnelModule;
27
+ }
8
28
 
9
29
  const name = "agentbridge-dsh-phone";
10
30
  // `agents` is not optional: creating a conversation from the phone asks the agent
@@ -200,7 +220,7 @@ async function startBridge(origin, log = () => {}, extraEnv = {}) {
200
220
  AGENTBRIDGE_AUTOSTART: "1",
201
221
  // The bridge only accepts a restart request carrying this token, which is how
202
222
  // the advertised address changes once a tunnel exists.
203
- AGENTBRIDGE_AUTOSTART_TOKEN: ensureAutostartToken(dataDir),
223
+ AGENTBRIDGE_AUTOSTART_TOKEN: (await tunnel()).ensureAutostartToken(dataDir),
204
224
  ...extraEnv,
205
225
  };
206
226
  // Under Electron `process.execPath` is DSH Desktop itself, not node: launching
@@ -279,6 +299,32 @@ function bridgeDataDir() {
279
299
  return process.env.AGENTBRIDGE_DATA_DIR || path.join(homedir(), ".agentbridge");
280
300
  }
281
301
 
302
+ /**
303
+ * The cloudflared to run, fetching the official build the first time.
304
+ *
305
+ * Remote mode is supposed to be the default, and "the default" cannot depend on
306
+ * the user having heard of cloudflared. So the machine is searched first (a real
307
+ * install wins, whoever put it there), and only when nothing is found does the
308
+ * plugin download Cloudflare's own binary into its data directory — no elevation,
309
+ * nothing in Program Files, removable by deleting one folder.
310
+ */
311
+ async function resolveCloudflared(log) {
312
+ const { findCloudflared, ensureCloudflared } = await tunnel();
313
+ const installed = findCloudflared({ env: process.env, home: homedir() });
314
+ if (installed) return installed;
315
+
316
+ log("cloudflared was not found; fetching the official build into the bridge's data directory (once)");
317
+ const downloaded = await ensureCloudflared({ dataDir: bridgeDataDir(), env: process.env, log });
318
+ if (!downloaded) {
319
+ log(
320
+ "still no cloudflared, so this machine stays on same-Wi-Fi pairing: "
321
+ + "install it with `winget install --id Cloudflare.cloudflared`, or download cloudflared-windows-amd64.exe "
322
+ + "from https://github.com/cloudflare/cloudflared/releases and point AGENTBRIDGE_CLOUDFLARED at it",
323
+ );
324
+ }
325
+ return downloaded;
326
+ }
327
+
282
328
  /**
283
329
  * The address the QR code should carry, and the key that unlocks it.
284
330
  *
@@ -290,12 +336,13 @@ async function resolveRemoteOrigin(log) {
290
336
  const explicit = String(process.env.AGENTBRIDGE_PUBLIC_ORIGIN ?? "").trim().replace(/\/$/, "");
291
337
  if (explicit) return { origin: explicit, accessKey: null, how: "AGENTBRIDGE_PUBLIC_ORIGIN" };
292
338
 
339
+ const { ensureAccessKey, startQuickTunnel } = await tunnel();
293
340
  const supplied = String(process.env.AGENTBRIDGE_TUNNEL_URL ?? "").trim().replace(/\/$/, "");
294
341
  if (supplied) return { origin: supplied, accessKey: ensureAccessKey(bridgeDataDir()), how: "AGENTBRIDGE_TUNNEL_URL" };
295
342
 
296
- const command = findCloudflared({ env: process.env, home: homedir() });
343
+ const command = await resolveCloudflared(log);
297
344
  if (!command) {
298
- log("no cloudflared found, staying on this Wi-Fi only: install it with `winget install --id Cloudflare.cloudflared`, then restart DSH Desktop");
345
+ log("no cloudflared is available, staying on this Wi-Fi only");
299
346
  return null;
300
347
  }
301
348
 
@@ -309,14 +356,14 @@ async function resolveRemoteOrigin(log) {
309
356
  }
310
357
 
311
358
  try {
312
- const tunnel = await startQuickTunnel({
359
+ const started = await startQuickTunnel({
313
360
  command,
314
361
  origin: `http://127.0.0.1:${port}`,
315
362
  dataDir: bridgeDataDir(),
316
363
  log,
317
364
  timeoutMs: TUNNEL_TIMEOUT_MS,
318
365
  });
319
- return { origin: tunnel.url, accessKey: ensureAccessKey(bridgeDataDir()), how: tunnel.reused ? "cloudflare (existing tunnel)" : "cloudflare" };
366
+ return { origin: started.url, accessKey: ensureAccessKey(bridgeDataDir()), how: started.reused ? "cloudflare (existing tunnel)" : "cloudflare" };
320
367
  } catch (error) {
321
368
  log(`cloudflare tunnel failed, staying on this Wi-Fi only: ${textFromError(error)}`);
322
369
  return null;
@@ -329,6 +376,7 @@ async function resolveRemoteOrigin(log) {
329
376
  * endpoint reports whether it was autostarted, and only that flag authorises this.
330
377
  */
331
378
  async function stopBridge(origin, log) {
379
+ const { readAutostartToken } = await tunnel();
332
380
  const token = readAutostartToken(bridgeDataDir());
333
381
  if (!token) {
334
382
  log("cannot restart the bridge: its autostart token is missing");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chenacc/dsh-agentbridge",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
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,7 +10,6 @@
10
10
  },
11
11
  "files": [
12
12
  "lib/index.js",
13
- "lib/tunnel.js",
14
13
  "cordis.patch.yml",
15
14
  "README.md",
16
15
  "LICENSE"
@@ -45,7 +44,7 @@
45
44
  }
46
45
  },
47
46
  "dependencies": {
48
- "@chenacc/agentbridge": "^0.1.3"
47
+ "@chenacc/agentbridge": "^0.1.4"
49
48
  },
50
49
  "peerDependencies": {
51
50
  "@deepseek-ai/dsh-commands": "^0.1.0-rc.7",
package/lib/tunnel.js DELETED
@@ -1,261 +0,0 @@
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
- export function autostartTokenPath(dataDir) {
78
- return path.join(dataDir, "autostart-token");
79
- }
80
-
81
- /**
82
- * The key that gates a publicly exposed bridge.
83
- *
84
- * Read before generated, so the value survives restarts: the phone already holds a
85
- * cookie for it, and regenerating on every launch would silently lock the phone
86
- * out of its own bridge.
87
- */
88
- export function ensureAccessKey(dataDir, { readFile = readFileSync, writeFile = writeFileSync, mkdir = mkdirSync, random } = {}) {
89
- return ensureSecret(accessKeyPath(dataDir), dataDir, { readFile, writeFile, mkdir, random });
90
- }
91
-
92
- /**
93
- * The secret that lets this plugin ask its own bridge to restart.
94
- *
95
- * A restart is how the advertised address changes (the tunnel hostname only
96
- * exists once cloudflared is up), and the bridge accepts that request only from
97
- * loopback *with this token* — so a random local page cannot stop the bridge, and
98
- * a second, unrelated DSH profile cannot either.
99
- */
100
- export function ensureAutostartToken(dataDir, options = {}) {
101
- return ensureSecret(autostartTokenPath(dataDir), dataDir, options);
102
- }
103
-
104
- export function readAutostartToken(dataDir, { readFile = readFileSync } = {}) {
105
- try {
106
- return String(readFile(autostartTokenPath(dataDir), "utf8")).trim() || null;
107
- } catch {
108
- return null;
109
- }
110
- }
111
-
112
- function ensureSecret(target, dataDir, { readFile = readFileSync, writeFile = writeFileSync, mkdir = mkdirSync, random } = {}) {
113
- try {
114
- const existing = String(readFile(target, "utf8")).trim();
115
- if (existing.length >= 16) return existing;
116
- } catch {
117
- // No usable secret on disk yet.
118
- }
119
- const secret = (random ?? (() => randomBytes(24).toString("base64url")))();
120
- mkdir(dataDir, { recursive: true });
121
- writeFile(target, secret, "utf8");
122
- return secret;
123
- }
124
-
125
- export function tunnelStatePath(dataDir) {
126
- return path.join(dataDir, "cloudflare-tunnel.json");
127
- }
128
-
129
- export function readTunnelState(dataDir, { readFile = readFileSync } = {}) {
130
- try {
131
- const parsed = JSON.parse(String(readFile(tunnelStatePath(dataDir), "utf8")));
132
- if (!parsed || typeof parsed.url !== "string" || !Number.isInteger(parsed.pid)) return null;
133
- return parsed;
134
- } catch {
135
- return null;
136
- }
137
- }
138
-
139
- export function writeTunnelState(dataDir, state, { writeFile = writeFileSync, mkdir = mkdirSync, rename = renameSync } = {}) {
140
- mkdir(dataDir, { recursive: true });
141
- const target = tunnelStatePath(dataDir);
142
- const temporary = `${target}.tmp`;
143
- writeFile(temporary, JSON.stringify(state, null, 2), "utf8");
144
- rename(temporary, target);
145
- return state;
146
- }
147
-
148
- function isAlive(pid, { kill = process.kill.bind(process) } = {}) {
149
- try {
150
- kill(pid, 0);
151
- return true;
152
- } catch (error) {
153
- // EPERM means "exists but not ours", which still counts as alive.
154
- return error?.code === "EPERM";
155
- }
156
- }
157
-
158
- /**
159
- * Start cloudflared and wait for the hostname it prints.
160
- *
161
- * The child is detached on purpose: the tunnel outliving DSH means the URL in an
162
- * already paired phone keeps working after the desktop restarts, and it also
163
- * avoids killing the tunnel whenever the Electron host decides to reload.
164
- *
165
- * Reuse is keyed on the state file plus a live pid plus a matching origin: a
166
- * tunnel pointing at the old port would advertise a URL that resolves to a 502.
167
- */
168
- export async function startQuickTunnel({
169
- command,
170
- origin,
171
- dataDir,
172
- log = () => {},
173
- timeoutMs = 40_000,
174
- spawnImpl = spawn,
175
- fetchImpl = globalThis.fetch,
176
- kill = process.kill.bind(process),
177
- } = {}) {
178
- if (!command) throw new Error("cloudflared was not found");
179
- if (!origin) throw new Error("the tunnel needs an origin to forward to");
180
-
181
- const previous = readTunnelState(dataDir);
182
- if (previous && previous.origin === origin && isAlive(previous.pid, { kill })) {
183
- const reachable = await probeTunnel(previous.url, fetchImpl);
184
- if (reachable) {
185
- log(`reusing the running Cloudflare tunnel at ${previous.url}`);
186
- return { ...previous, reused: true };
187
- }
188
- log(`the recorded tunnel is no longer answering; starting a new one`);
189
- }
190
-
191
- const child = spawnImpl(command, ["tunnel", "--no-autoupdate", "--url", origin], {
192
- detached: true,
193
- windowsHide: true,
194
- stdio: ["ignore", "pipe", "pipe"],
195
- });
196
-
197
- const state = await new Promise((resolve, reject) => {
198
- let output = "";
199
- let settled = false;
200
-
201
- const finish = (error, value) => {
202
- if (settled) return;
203
- settled = true;
204
- clearTimeout(timer);
205
- if (error) reject(error);
206
- else resolve(value);
207
- };
208
-
209
- const timer = setTimeout(() => {
210
- const tail = output.trim().split(/\r?\n/).slice(-6).join(" | ");
211
- try {
212
- kill(child.pid, "SIGKILL");
213
- } catch {
214
- // Already gone.
215
- }
216
- finish(new Error(`cloudflared did not announce a hostname within ${Math.round(timeoutMs / 1000)}s${tail ? `: ${tail}` : ""}`));
217
- }, timeoutMs);
218
- timer.unref?.();
219
-
220
- const onData = (chunk) => {
221
- output += String(chunk);
222
- const url = extractTunnelUrl(output);
223
- if (!url) return;
224
- finish(null, {
225
- url,
226
- pid: child.pid,
227
- origin,
228
- startedAt: new Date().toISOString(),
229
- });
230
- };
231
-
232
- child.stdout?.on?.("data", onData);
233
- child.stderr?.on?.("data", onData);
234
- child.once?.("error", (error) => finish(new Error(`cloudflared could not start: ${error.message}`)));
235
- child.once?.("exit", (code) => {
236
- const tail = output.trim().split(/\r?\n/).slice(-6).join(" | ");
237
- finish(new Error(`cloudflared exited with code ${code} before announcing a hostname${tail ? `: ${tail}` : ""}`));
238
- });
239
- });
240
-
241
- // The tunnel is meant to outlive this process; the pipes are only for the banner.
242
- child.unref?.();
243
- child.stdout?.destroy?.();
244
- child.stderr?.destroy?.();
245
- return writeTunnelState(dataDir, state) && { ...state, reused: false };
246
- }
247
-
248
- /**
249
- * Anything but a transport error means the tunnel exists.
250
- *
251
- * A 502 is the normal answer while the local bridge is down, and it still proves
252
- * Cloudflare's edge knows this hostname.
253
- */
254
- async function probeTunnel(url, fetchImpl = globalThis.fetch) {
255
- try {
256
- await fetchImpl(`${url}/api/health`, { signal: AbortSignal.timeout(6_000) });
257
- return true;
258
- } catch {
259
- return false;
260
- }
261
- }