@chenacc/dsh-agentbridge 0.2.1 → 0.2.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.
Files changed (2) hide show
  1. package/lib/index.js +81 -20
  2. package/package.json +1 -1
package/lib/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { existsSync } from "node:fs";
2
+ import { closeSync, existsSync, mkdirSync, openSync } from "node:fs";
3
+ import { createRequire } from "node:module";
3
4
  import { homedir } from "node:os";
4
5
  import path from "node:path";
5
6
  import { fileURLToPath } from "node:url";
@@ -90,6 +91,11 @@ const AUTOSTART_TIMEOUT_MS = 8_000;
90
91
  * comes from module resolution next to this file. `AGENTBRIDGE_BRIDGE_ENTRY`
91
92
  * exists for tests and for unusual installs.
92
93
  *
94
+ * Resolution goes through `createRequire` first on purpose: `import.meta.resolve`
95
+ * only exists from Node 20.6, and the Electron runtime DSH Desktop loads plugins
96
+ * in can be older than that — an unresolvable answer there fails silently and
97
+ * looks exactly like "no bridge installed".
98
+ *
93
99
  * The resolved manifest must live under a `node_modules` directory: without that
94
100
  * check, Node's package self-reference resolves this repository's own root
95
101
  * package as `@chenacc/agentbridge`, so a development checkout would start a
@@ -97,13 +103,27 @@ const AUTOSTART_TIMEOUT_MS = 8_000;
97
103
  */
98
104
  function bridgeServerEntry() {
99
105
  if (process.env.AGENTBRIDGE_BRIDGE_ENTRY) return process.env.AGENTBRIDGE_BRIDGE_ENTRY;
106
+
107
+ const candidates = [];
100
108
  try {
101
- const resolved = fileURLToPath(import.meta.resolve(`${BRIDGE_PACKAGE}/package.json`));
102
- if (!resolved.split(path.sep).includes("node_modules")) return null;
103
- return path.join(path.dirname(resolved), "src", "server.js");
109
+ candidates.push(createRequire(import.meta.url).resolve(`${BRIDGE_PACKAGE}/package.json`));
104
110
  } catch {
105
- return null;
111
+ // Not installed next to the plugin: fall through to the ESM resolver.
106
112
  }
113
+ try {
114
+ if (typeof import.meta.resolve === "function") {
115
+ candidates.push(fileURLToPath(import.meta.resolve(`${BRIDGE_PACKAGE}/package.json`)));
116
+ }
117
+ } catch {
118
+ // No ESM resolver either: the dependency is simply absent.
119
+ }
120
+
121
+ for (const manifest of candidates) {
122
+ if (!manifest.split(path.sep).includes("node_modules")) continue;
123
+ const entry = path.join(path.dirname(manifest), "src", "server.js");
124
+ if (existsSync(entry)) return entry;
125
+ }
126
+ return null;
107
127
  }
108
128
 
109
129
  async function bridgeIsReady(origin) {
@@ -135,22 +155,53 @@ function autoStartAllowed() {
135
155
  * Start the local bridge and wait until it answers.
136
156
  *
137
157
  * Returns true only once the health check passes, so the caller retries the real
138
- * registration instead of trusting that a spawn means a working server. Every
139
- * failure path is silent: the caller falls back to the manual setup text.
158
+ * registration instead of trusting that a spawn means a working server. Failures
159
+ * stay quiet for the user (they get the manual steps either way) but each one is
160
+ * reported through `log`, because "nothing happened" is the hardest thing to
161
+ * diagnose from the outside.
140
162
  */
141
- async function startBridge(origin) {
163
+ async function startBridge(origin, log = () => {}) {
142
164
  if (await bridgeIsReady(origin)) return true;
143
- if (!autoStartAllowed()) return false;
165
+ if (!autoStartAllowed()) {
166
+ log("auto-start disabled for this process");
167
+ return false;
168
+ }
144
169
  const entry = bridgeServerEntry();
145
- if (!entry || !existsSync(entry)) return false;
170
+ if (!entry || !existsSync(entry)) {
171
+ log(`auto-start skipped: ${BRIDGE_PACKAGE} is not resolvable from the plugin install`);
172
+ return false;
173
+ }
146
174
 
147
175
  let port;
148
176
  try {
149
177
  port = new URL(origin).port || "8787";
150
178
  } catch {
179
+ log(`auto-start skipped: ${origin} is not a usable origin`);
151
180
  return false;
152
181
  }
153
182
 
183
+ const dataDir = process.env.AGENTBRIDGE_DATA_DIR || path.join(homedir(), ".agentbridge");
184
+ const env = {
185
+ ...process.env,
186
+ AGENTBRIDGE_PORT: process.env.AGENTBRIDGE_PORT || port,
187
+ AGENTBRIDGE_DATA_DIR: dataDir,
188
+ };
189
+ // Under Electron `process.execPath` is DSH Desktop itself, not node: launching
190
+ // it with a .js path starts the app again and no server ever binds. Electron
191
+ // ships a Node runtime behind ELECTRON_RUN_AS_NODE, which is exactly this.
192
+ if (process.versions.electron) env.ELECTRON_RUN_AS_NODE = "1";
193
+
194
+ // Keep the child's own output: when a spawned bridge dies, its stderr is the
195
+ // only place that says why (port in use, missing module, bad config).
196
+ let logFd = "ignore";
197
+ try {
198
+ const logDir = path.join(dataDir, "logs");
199
+ mkdirSync(logDir, { recursive: true });
200
+ logFd = openSync(path.join(logDir, "autostart.log"), "a");
201
+ } catch {
202
+ // No writable data dir: run without output capture rather than not at all.
203
+ }
204
+
154
205
  try {
155
206
  // Loaded lazily: the plugin normally runs with a bridge already up, so the
156
207
  // child-process machinery is dead weight on the common path.
@@ -163,17 +214,22 @@ async function startBridge(origin) {
163
214
  // some internal folder.
164
215
  cwd: homedir(),
165
216
  detached: true,
166
- stdio: "ignore",
217
+ stdio: ["ignore", logFd, logFd],
167
218
  windowsHide: true,
168
- env: {
169
- ...process.env,
170
- AGENTBRIDGE_PORT: process.env.AGENTBRIDGE_PORT || port,
171
- AGENTBRIDGE_DATA_DIR: process.env.AGENTBRIDGE_DATA_DIR || path.join(homedir(), ".agentbridge"),
172
- },
219
+ env,
173
220
  });
174
221
  child.unref();
175
- } catch {
222
+ } catch (error) {
223
+ log(`auto-start failed to spawn ${entry}: ${textFromError(error)}`);
176
224
  return false;
225
+ } finally {
226
+ if (typeof logFd === "number") {
227
+ try {
228
+ closeSync(logFd);
229
+ } catch {
230
+ // The child holds its own duplicate; nothing to recover here.
231
+ }
232
+ }
177
233
  }
178
234
 
179
235
  const deadline = Date.now() + AUTOSTART_TIMEOUT_MS;
@@ -181,6 +237,7 @@ async function startBridge(origin) {
181
237
  await new Promise((resolve) => setTimeout(resolve, 150));
182
238
  if (await bridgeIsReady(origin)) return true;
183
239
  }
240
+ log(`auto-start timed out: spawned ${entry} but ${origin} never answered`);
184
241
  return false;
185
242
  }
186
243
 
@@ -969,9 +1026,13 @@ function apply(ctx) {
969
1026
 
970
1027
  // Bring the bridge up in the background as soon as the plugin loads, so by the
971
1028
  // time the user types /phone the local service is already there. Deliberately
972
- // not awaited: a slow spawn must never delay desktop startup, and every failure
973
- // is silent — /phone still prints the manual steps when nothing came up.
974
- void startBridge(String(process.env.AGENTBRIDGE_ORIGIN || DEFAULT_ORIGIN).replace(/\/$/, "")).catch(() => {});
1029
+ // not awaited: a slow spawn must never delay desktop startup, and the user
1030
+ // still gets the manual steps from /phone when nothing came up. The reason is
1031
+ // logged instead of swallowed, because "nothing happened" is undiagnosable.
1032
+ void startBridge(
1033
+ String(process.env.AGENTBRIDGE_ORIGIN || DEFAULT_ORIGIN).replace(/\/$/, ""),
1034
+ (message) => ctx.logger?.warn?.(`[agentbridge-dsh-phone] ${message}`),
1035
+ ).catch((error) => ctx.logger?.warn?.(`[agentbridge-dsh-phone] auto-start crashed: ${textFromError(error)}`));
975
1036
  }
976
1037
 
977
1038
  export { apply, inject, name };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chenacc/dsh-agentbridge",
3
- "version": "0.2.1",
3
+ "version": "0.2.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",