@chenacc/dsh-agentbridge 0.4.4 → 0.4.6

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 +219 -16
  2. package/package.json +2 -2
package/lib/index.js CHANGED
@@ -44,7 +44,33 @@ const name = "agentbridge-dsh-phone";
44
44
  // service to open one, and touching a service that was not injected throws
45
45
  // `cannot get property "agents" without inject` — which is what the phone showed
46
46
  // as a failed "新建对话" instead of the friendly message below.
47
- const inject = ["commands", "apiProxy", "llm", "agents"];
47
+ //
48
+ // `apiProxy` is deliberately NOT in this list. It was a 0.1.x desktop service and
49
+ // DSH 0.2.x no longer provides it — a required entry for a service that does not
50
+ // exist keeps the whole plugin "pending (waiting for service: apiProxy)" forever,
51
+ // so `/phone` never registers. It is read through `ctx.get()`, which returns
52
+ // undefined instead of throwing, and the features that need it degrade with a
53
+ // message rather than blocking the entire plugin.
54
+ const inject = ["commands", "llm", "agents"];
55
+
56
+ /** The 0.1.x desktop RPC bridge, when this host still has one. */
57
+ function apiProxyOf(ctx) {
58
+ // `ctx.get` reads the service store without an inject requirement and returns
59
+ // undefined when nothing provides it. The property fallback keeps plain-object
60
+ // contexts (tests, and any host that hands a bare object) working, while the
61
+ // catch absorbs cordis' `cannot get property "apiProxy" without inject`.
62
+ try {
63
+ const provided = ctx.get?.("apiProxy");
64
+ if (provided) return provided;
65
+ } catch {
66
+ // No service store on this context.
67
+ }
68
+ try {
69
+ return ctx.apiProxy ?? null;
70
+ } catch {
71
+ return null;
72
+ }
73
+ }
48
74
  const DEFAULT_ORIGIN = "http://127.0.0.1:8787";
49
75
  const POLL_DELAY_MS = 800;
50
76
  const EVENT_BATCH_DELAY_MS = 120;
@@ -400,30 +426,43 @@ async function bringUpBridge(log) {
400
426
  const origin = localOrigin();
401
427
  await startBridge(origin, log);
402
428
  if (!remoteAllowed()) return;
429
+ await applyRemoteAddress(origin, log);
430
+ }
403
431
 
432
+ /**
433
+ * Try to move the running bridge onto the resolved address.
434
+ *
435
+ * Returns "done" when the advertised address is already right or was just set,
436
+ * and otherwise names the reason, which is what `/phone` explains to the user
437
+ * (a stray bridge on the port, no usable path, a stop that was refused). There is
438
+ * deliberately no background retry: the decision costs a tunnel, and a loop that
439
+ * keeps opening them would be worse than a stale address the user can fix by
440
+ * restarting the desktop.
441
+ */
442
+ async function applyRemoteAddress(origin, log) {
404
443
  const health = await bridgeHealth(origin);
405
- if (!health) return; // startBridge already logged why nothing came up.
444
+ if (!health) return "no-bridge"; // startBridge already logged why nothing came up.
406
445
 
407
446
  const remote = await resolveRemoteOrigin(log);
408
- if (!remote) return;
447
+ if (!remote) return "no-path";
409
448
  if (health.advertisedOrigin === remote.origin && (!remote.accessKey || health.accessKeyRequired === true)) {
410
- log(`remote mode already active: ${remote.origin}`);
411
- return;
449
+ return "done";
412
450
  }
413
451
  if (health.autostart !== true) {
414
452
  log(
415
453
  `the bridge already running at ${origin} was not started by this plugin, so its address cannot be changed. `
416
- + `Stop it (or restart DSH Desktop after closing it) to switch to ${remote.origin}.`,
454
+ + `Stop it (or close it and restart DSH Desktop) to switch to ${remote.origin}.`,
417
455
  );
418
- return;
456
+ return "foreign-bridge";
419
457
  }
420
- if (!(await stopBridge(origin, log))) return;
458
+ if (!(await stopBridge(origin, log))) return "stop-failed";
421
459
  if (await startBridge(origin, log, remoteEnv(remote))) {
422
460
  log(`remote mode ready: ${remote.origin} (via ${remote.how})`);
423
- return;
461
+ return "done";
424
462
  }
425
463
  log("the bridge did not come up with the public address, restarting it on this Wi-Fi only");
426
464
  await startBridge(origin, log);
465
+ return "start-failed";
427
466
  }
428
467
 
429
468
  function clipped(value, limit) {
@@ -608,6 +647,17 @@ export class PhoneConnections {
608
647
  this.liveModelSelections = new WeakMap();
609
648
  this.ctx.on("session/event", (session, event) => this.captureEvent(session, event));
610
649
  this.ctx.on("agent/disposed", ({ agent }) => this.dispose(agent.session.id));
650
+ // A conversation reopened inside the desktop app gets a fresh agent; if the
651
+ // bridge already holds a paired session for it, re-attach without waiting for
652
+ // a human to run /phone again. This is what makes a DSH Desktop update
653
+ // invisible to the phone.
654
+ this.ctx.on("agent/created", (payload) => {
655
+ const agent = payload?.agent ?? payload;
656
+ if (agent?.session?.id) void this.#restoreChannel(agent);
657
+ });
658
+ // The bridge answers with the conversation ids it is waiting on; a short
659
+ // cache keeps a burst of reopened conversations from each asking.
660
+ this.expectedCache = null;
611
661
  }
612
662
 
613
663
  lifetimeFor(sessionId) {
@@ -629,6 +679,9 @@ export class PhoneConnections {
629
679
  // A reconnect must not consume a pairing code or add a device: the phone that
630
680
  // already owns this conversation keeps owning it.
631
681
  const reconnecting = options.reconnecting === true;
682
+ // A restore after the desktop restarted: attach the bridge session that
683
+ // already exists, never mint one for a conversation the phone never paired.
684
+ const existingOnly = options.existingOnly === true;
632
685
  const response = await fetch(`${origin}/api/local/dsh-desktop/register`, {
633
686
  method: "POST",
634
687
  headers: { "content-type": "application/json" },
@@ -642,6 +695,7 @@ export class PhoneConnections {
642
695
  integrationVersion: INTEGRATION_VERSION,
643
696
  ...(bridgeSessionId ? { bridgeSessionId } : {}),
644
697
  ...(reconnecting ? { reconnect: true } : {}),
698
+ ...(existingOnly ? { existingOnly: true } : {}),
645
699
  }),
646
700
  });
647
701
  const registration = await readResponse(response);
@@ -711,6 +765,102 @@ export class PhoneConnections {
711
765
  })().finally(() => { state.reconnecting = null; });
712
766
  return state.reconnecting;
713
767
  }
768
+
769
+ /**
770
+ * Re-attach the conversations a restarted desktop app is opening again.
771
+ *
772
+ * After DSH Desktop updates or restarts, the bridge still has every paired
773
+ * session and its history, but the desktop-side channel is gone. This asks the
774
+ * bridge which conversations are waiting for a companion, matches them against
775
+ * the agents this process has live, and re-registers only those. Conversations
776
+ * that were never paired are left alone, so opening them cannot mint new
777
+ * sessions on the phone.
778
+ */
779
+ async restoreKnownConversations() {
780
+ const expected = await this.#expectedConversationsWithRetry();
781
+ if (!expected || expected.size === 0) return 0;
782
+ let restored = 0;
783
+ for (const agent of this.#liveAgents()) {
784
+ const sessionId = agent?.session?.id;
785
+ if (!sessionId || this.bySession.has(sessionId) || !expected.has(sessionId)) continue;
786
+ try {
787
+ await this.connect(agent, { reconnecting: true, existingOnly: true });
788
+ restored += 1;
789
+ } catch (error) {
790
+ this.ctx.logger?.warn?.(`AgentBridge: could not restore the phone channel for "${agent.session.header?.title ?? sessionId}": ${textFromError(error)}`);
791
+ }
792
+ }
793
+ if (restored > 0) {
794
+ this.ctx.logger?.warn?.(`AgentBridge: restored ${restored} phone conversation${restored === 1 ? "" : "s"} after the desktop restarted`);
795
+ }
796
+ return restored;
797
+ }
798
+
799
+ async #restoreChannel(agent) {
800
+ const sessionId = agent?.session?.id;
801
+ if (!sessionId || this.bySession.has(sessionId)) return;
802
+ try {
803
+ const expected = await this.#expectedConversationsWithRetry();
804
+ if (!expected || !expected.has(sessionId) || this.bySession.has(sessionId)) return;
805
+ await this.connect(agent, { reconnecting: true, existingOnly: true });
806
+ this.ctx.logger?.warn?.(`AgentBridge: restored the phone channel for "${agent.session.header?.title ?? sessionId}" after the desktop restarted`);
807
+ } catch (error) {
808
+ this.ctx.logger?.warn?.(`AgentBridge: could not restore the phone channel: ${textFromError(error)}`);
809
+ }
810
+ }
811
+
812
+ #liveAgents() {
813
+ let agents;
814
+ try {
815
+ agents = this.ctx.agents ?? null;
816
+ } catch {
817
+ agents = null;
818
+ }
819
+ try {
820
+ return typeof agents?.list === "function" ? agents.list() : [];
821
+ } catch {
822
+ return [];
823
+ }
824
+ }
825
+
826
+ /**
827
+ * The conversations the bridge is waiting to hear from again.
828
+ *
829
+ * Fetched over loopback, cached briefly so several agents opening at once do
830
+ * not each ask. The register call remains the authority: the bridge refuses
831
+ * an id it has no session for, so a stale set is harmless.
832
+ */
833
+ async #expectedConversations() {
834
+ const now = Date.now();
835
+ if (this.expectedCache && now - this.expectedCache.at < 5_000) return this.expectedCache.set;
836
+ const response = await fetch(`${localOrigin()}/api/local/dsh-desktop/expected`, {
837
+ signal: AbortSignal.timeout(1_500),
838
+ });
839
+ if (!response.ok) return null;
840
+ const body = await response.json().catch(() => null);
841
+ const set = new Set(Array.isArray(body?.providerSessionIds) ? body.providerSessionIds : []);
842
+ this.expectedCache = { at: now, set };
843
+ return set;
844
+ }
845
+
846
+ /**
847
+ * The bridge may still be starting when a conversation is opened moments after
848
+ * an update, so a failed probe is retried for a few seconds instead of being
849
+ * lost. This is loopback-only, so it does not wait on a tunnel.
850
+ */
851
+ async #expectedConversationsWithRetry({ timeoutMs = 6_000 } = {}) {
852
+ const deadline = Date.now() + timeoutMs;
853
+ for (;;) {
854
+ try {
855
+ const expected = await this.#expectedConversations();
856
+ if (expected !== null) return expected;
857
+ } catch {
858
+ // The bridge is not listening yet.
859
+ }
860
+ if (Date.now() >= deadline) return null;
861
+ await new Promise((resolve) => setTimeout(resolve, 300));
862
+ }
863
+ }
714
864
  // Interaction retries live on the *lifetime*, not on the channel state. A reconnect
715
865
  // (or a dropped channel) throws the state away; a question that failed to cross the
716
866
  // wire must survive that, otherwise the phone sees the card a second after the
@@ -729,7 +879,7 @@ export class PhoneConnections {
729
879
  // through `apiProxy.respond`. Same seam the desktop window uses, which is what
730
880
  // lets a phone answer a question the desktop is also showing.
731
881
  async watchInteractions(state) {
732
- const events = this.ctx.apiProxy?.events;
882
+ const events = apiProxyOf(this.ctx)?.events;
733
883
  if (typeof events?.mux !== "function") return;
734
884
  const sessionId = state.agent.session.id;
735
885
  const scope = this.#interactionScope(sessionId);
@@ -818,14 +968,17 @@ export class PhoneConnections {
818
968
  }
819
969
 
820
970
  async respond(rpcId, result) {
821
- if (typeof this.ctx.apiProxy?.respond !== "function") throw new Error("This DSH Desktop build cannot answer questions from the phone");
822
- return await this.ctx.apiProxy.respond({ type: "client-response", rpcId, result });
971
+ const apiProxy = apiProxyOf(this.ctx);
972
+ if (typeof apiProxy?.respond !== "function") throw new Error("This DSH Desktop build cannot answer questions from the phone");
973
+ return await apiProxy.respond({ type: "client-response", rpcId, result });
823
974
  }
824
975
 
825
976
  async modelDirectory(agent) {
826
977
  const current = selectionFromAgent(agent);
827
978
  try {
828
- const response = await this.ctx.apiProxy.sessions.models({
979
+ const apiProxy = apiProxyOf(this.ctx);
980
+ if (typeof apiProxy?.sessions?.models !== "function") return current;
981
+ const response = await apiProxy.sessions.models({
829
982
  rpcId: randomUUID(),
830
983
  payload: { sessionId: agent.session.id },
831
984
  });
@@ -848,7 +1001,11 @@ export class PhoneConnections {
848
1001
  }
849
1002
 
850
1003
  async hostModelDirectory(current, sessionError) {
851
- const response = await this.ctx.apiProxy.llm.models({ rpcId: randomUUID(), payload: {} });
1004
+ const apiProxy = apiProxyOf(this.ctx);
1005
+ if (typeof apiProxy?.llm?.models !== "function") {
1006
+ throw new Error("DSH Desktop did not provide its host model directory");
1007
+ }
1008
+ const response = await apiProxy.llm.models({ rpcId: randomUUID(), payload: {} });
852
1009
  const result = response?.result;
853
1010
  if (!result?.ok) throw new Error(result?.error?.message || "DSH Desktop did not provide its host model directory");
854
1011
  return compactModelDirectory(result.value, current, [{
@@ -886,7 +1043,20 @@ export class PhoneConnections {
886
1043
  }
887
1044
 
888
1045
  async selectModel(agent, requested) {
889
- const response = await this.ctx.apiProxy.sessions.selectModel({
1046
+ const apiProxy = apiProxyOf(this.ctx);
1047
+ if (typeof apiProxy?.sessions?.selectModel !== "function") {
1048
+ // 0.2.x hosts have no desktop RPC bridge; the host-side llm service is the
1049
+ // remaining source of truth for which models can be selected.
1050
+ const resolved = await this.ctx.llm.resolveCallConfig(requested);
1051
+ const selected = {
1052
+ provider: resolved?.provider ?? requested.provider,
1053
+ model: resolved?.model ?? requested.model,
1054
+ ...(resolved?.reasoningEffort ? { reasoningEffort: resolved.reasoningEffort } : {}),
1055
+ };
1056
+ this.liveModelSelections.set(agent, selected);
1057
+ return selected;
1058
+ }
1059
+ const response = await apiProxy.sessions.selectModel({
890
1060
  rpcId: randomUUID(),
891
1061
  payload: { sessionId: agent.session.id, ...requested },
892
1062
  });
@@ -1195,6 +1365,27 @@ function pairingAddressNote(url) {
1195
1365
  return "这是公网地址,手机用流量也能打开;二维码里已带访问密钥,别把它转发给别人。";
1196
1366
  }
1197
1367
 
1368
+ /**
1369
+ * Why this QR code is a LAN address, when the user expects a public one.
1370
+ *
1371
+ * The address is decided once, when the plugin loads: it starts its own bridge and
1372
+ * then restarts that child onto the tunnel address. A bridge on 8787 it did not
1373
+ * start (a manual `npx`/`npm start`, or a leftover from an earlier session) is
1374
+ * never restarted, because that would cut whatever is running on it — so the QR
1375
+ * code quietly stays on the LAN. That explanation belongs in the answer, not only
1376
+ * in the desktop log.
1377
+ */
1378
+ function lanOnlyReason(health) {
1379
+ if (!health) return null;
1380
+ if (health.autostart === false) {
1381
+ return "当前是局域网地址:8787 上运行着一个不是本插件启动的桥(比如你手动跑过 npx / npm start)。插件不会去重启别人的进程,所以没有切到公网。停掉它再重启 DSH Desktop 就会切过去。";
1382
+ }
1383
+ if (health.advertisedOrigin && !health.remoteProvider) {
1384
+ return "当前是局域网地址:这次启动时没能建立起公网通道。具体原因在 DSH 的日志里(搜 [agentbridge-dsh-phone]),常见是 cloudflared 没装好或网络被拦。";
1385
+ }
1386
+ return null;
1387
+ }
1388
+
1198
1389
  function apply(ctx) {
1199
1390
  const connections = new PhoneConnections(ctx);
1200
1391
  ctx.commands.register({
@@ -1208,6 +1399,8 @@ function apply(ctx) {
1208
1399
  try {
1209
1400
  const registration = await connections.connect(agent);
1210
1401
  const model = [agent.options.provider, agent.options.model].filter(Boolean).join(" / ") || "当前 DSH 配置";
1402
+ const health = await bridgeHealth(localOrigin()).catch(() => null);
1403
+ const lanReason = health?.remoteProvider ? null : lanOnlyReason(health);
1211
1404
  return {
1212
1405
  kind: "success",
1213
1406
  text: [
@@ -1218,6 +1411,7 @@ function apply(ctx) {
1218
1411
  `会话:${agent.session.id}`,
1219
1412
  `模型:${model}`,
1220
1413
  pairingAddressNote(registration.pairing.url),
1414
+ ...(lanReason ? [lanReason] : []),
1221
1415
  // A one-line, no-strings ask. Nothing fires on the user's behalf —
1222
1416
  // market ranking reads stars, so this is where a willing user can
1223
1417
  // help without leaving the conversation.
@@ -1243,7 +1437,16 @@ function apply(ctx) {
1243
1437
  // when nothing came up. The reason is logged instead of swallowed, because
1244
1438
  // "nothing happened" is undiagnosable.
1245
1439
  void bringUpBridge((message) => ctx.logger?.warn?.(`[agentbridge-dsh-phone] ${message}`))
1246
- .catch((error) => ctx.logger?.warn?.(`[agentbridge-dsh-phone] auto-start crashed: ${textFromError(error)}`));
1440
+ .catch((error) => ctx.logger?.warn?.(`[agentbridge-dsh-phone] auto-start crashed: ${textFromError(error)}`))
1441
+ // Once the bridge is up (or its start failed), recover any conversation the
1442
+ // desktop app reopened after an update: the phone should not notice a
1443
+ // restart it did not ask for. Conversations opened later arrive as
1444
+ // `agent/created` events instead.
1445
+ .finally(() => {
1446
+ void connections.restoreKnownConversations().catch((error) => {
1447
+ ctx.logger?.warn?.(`[agentbridge-dsh-phone] restore of known conversations failed: ${textFromError(error)}`);
1448
+ });
1449
+ });
1247
1450
  }
1248
1451
 
1249
1452
  export { apply, inject, name };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chenacc/dsh-agentbridge",
3
- "version": "0.4.4",
3
+ "version": "0.4.6",
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",
@@ -46,7 +46,7 @@
46
46
  }
47
47
  },
48
48
  "dependencies": {
49
- "@chenacc/agentbridge": "^0.2.3"
49
+ "@chenacc/agentbridge": "^0.2.4"
50
50
  },
51
51
  "peerDependencies": {
52
52
  "@deepseek-ai/dsh-commands": ">=0.1.0-rc.7 <0.3.0",