@chenacc/dsh-agentbridge 0.4.7 → 0.4.9

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.
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Holds approval decisions that are waiting on a phone.
3
+ *
4
+ * DSH asks for permission through a hook that expects an answer in return — the tool
5
+ * call is suspended until someone says yes or no. The phone is not in that call stack,
6
+ * so the plugin parks a promise here, shows a card, and resolves the promise when the
7
+ * decision comes back over the bridge.
8
+ *
9
+ * Two things must never leak: a promise that nobody ever settles (the turn would hang
10
+ * forever) and a decision delivered after the fact (it would answer the wrong card).
11
+ * So every waiter is either resolved, rejected by timeout, or cancelled with its turn.
12
+ */
13
+
14
+ /** Outcomes DSH understands for an approval. */
15
+ export const APPROVAL_OUTCOMES = Object.freeze(["allowed-once", "rejected", "cancelled", "unavailable"]);
16
+
17
+ export function normalizeApprovalOutcome(value) {
18
+ return APPROVAL_OUTCOMES.includes(value) ? value : "rejected";
19
+ }
20
+
21
+ export class ApprovalBroker {
22
+ #waiters = new Map();
23
+
24
+ constructor({ now = () => Date.now(), timeoutMs = 5 * 60_000 } = {}) {
25
+ this.now = now;
26
+ this.timeoutMs = timeoutMs;
27
+ }
28
+
29
+ get size() {
30
+ return this.#waiters.size;
31
+ }
32
+
33
+ has(id) {
34
+ return this.#waiters.has(id);
35
+ }
36
+
37
+ /**
38
+ * Wait for the decision on `id`.
39
+ *
40
+ * Resolves with one of {@link APPROVAL_OUTCOMES}. A timeout resolves as `cancelled`
41
+ * rather than `rejected`: nobody declined, the chance simply expired, and the turn
42
+ * should say that instead of claiming the user refused.
43
+ */
44
+ wait(id, { signal } = {}) {
45
+ if (this.#waiters.has(id)) throw new Error(`approval ${id} is already pending`);
46
+ return new Promise((resolve) => {
47
+ const finish = (outcome) => {
48
+ const waiter = this.#waiters.get(id);
49
+ if (!waiter) return;
50
+ this.#waiters.delete(id);
51
+ clearTimeout(waiter.timer);
52
+ if (signal && waiter.onAbort) signal.removeEventListener("abort", waiter.onAbort);
53
+ resolve(normalizeApprovalOutcome(outcome));
54
+ };
55
+ const waiter = {
56
+ timer: setTimeout(() => finish("cancelled"), this.timeoutMs),
57
+ resolve: finish,
58
+ };
59
+ if (typeof waiter.timer.unref === "function") waiter.timer.unref();
60
+ if (signal) {
61
+ if (signal.aborted) {
62
+ clearTimeout(waiter.timer);
63
+ resolve("cancelled");
64
+ return;
65
+ }
66
+ waiter.onAbort = () => finish("cancelled");
67
+ signal.addEventListener("abort", waiter.onAbort, { once: true });
68
+ }
69
+ this.#waiters.set(id, waiter);
70
+ });
71
+ }
72
+
73
+ /** Deliver a decision. False when the card is gone (already answered or expired). */
74
+ resolve(id, outcome) {
75
+ const waiter = this.#waiters.get(id);
76
+ if (!waiter) return false;
77
+ waiter.resolve(outcome);
78
+ return true;
79
+ }
80
+
81
+ cancel(id) {
82
+ return this.resolve(id, "cancelled");
83
+ }
84
+
85
+ cancelAll() {
86
+ for (const id of [...this.#waiters.keys()]) this.cancel(id);
87
+ }
88
+ }
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 { ApprovalBroker } from "./approval-broker.js";
7
8
 
8
9
  /**
9
10
  * The tunnel and path-selection machinery lives in the bridge package, because
@@ -53,6 +54,21 @@ const name = "agentbridge-dsh-phone";
53
54
  // message rather than blocking the entire plugin.
54
55
  const inject = ["commands", "llm", "agents"];
55
56
 
57
+ /** DSH's permission presets, read the same defensive way as `apiProxy`. */
58
+ function permissionServiceOf(ctx) {
59
+ try {
60
+ const provided = ctx.get?.("permissionPresets");
61
+ if (provided) return provided;
62
+ } catch {
63
+ // No service store on this context.
64
+ }
65
+ try {
66
+ return ctx.permissionPresets ?? null;
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+
56
72
  /** The 0.1.x desktop RPC bridge, when this host still has one. */
57
73
  function apiProxyOf(ctx) {
58
74
  // `ctx.get` reads the service store without an inject requirement and returns
@@ -645,7 +661,16 @@ export class PhoneConnections {
645
661
  // conversation, not to the channel that tried to carry them.
646
662
  this.interactionScopes = new Map();
647
663
  this.liveModelSelections = new WeakMap();
664
+ // Approvals DSH is waiting on. The phone answers out of band, so the question is
665
+ // parked here until the card comes back — see approval-broker.js.
666
+ this.approvals = new ApprovalBroker();
667
+ this.approvalIds = new Map();
648
668
  this.ctx.on("session/event", (session, event) => this.captureEvent(session, event));
669
+ // DSH 0.2.x asks for permission through a waterfall event and waits for a return
670
+ // value; the desktop window answers through the same event. With no live phone
671
+ // channel this returns "unavailable" immediately, so the desktop behaves exactly as
672
+ // it did before this listener existed.
673
+ this.ctx.on("approval/request", (request) => this.approvalRequest(request));
649
674
  this.ctx.on("agent/disposed", ({ agent }) => this.dispose(agent.session.id));
650
675
  // A conversation reopened inside the desktop app gets a fresh agent; if the
651
676
  // bridge already holds a paired session for it, re-attach without waiting for
@@ -692,6 +717,7 @@ export class PhoneConnections {
692
717
  provider: agent.options.provider,
693
718
  model: agent.options.model,
694
719
  modelDirectory,
720
+ permissionDirectory: this.permissionDirectory(agent),
695
721
  integrationVersion: INTEGRATION_VERSION,
696
722
  ...(bridgeSessionId ? { bridgeSessionId } : {}),
697
723
  ...(reconnecting ? { reconnect: true } : {}),
@@ -973,6 +999,57 @@ export class PhoneConnections {
973
999
  return await apiProxy.respond({ type: "client-response", rpcId, result });
974
1000
  }
975
1001
 
1002
+ /**
1003
+ * The permission presets this deployment offers, plus the one in force here.
1004
+ *
1005
+ * DSH's "permission" is two knobs — sandbox level and approval policy — bundled as
1006
+ * presets by the `permissionPresets` service. The phone only needs names and labels;
1007
+ * the sandbox level travels along so a reader can tell what a preset actually allows.
1008
+ */
1009
+ permissionDirectory(agent) {
1010
+ const service = permissionServiceOf(this.ctx);
1011
+ const catalog = typeof service?.catalog === "function" ? service.catalog() : [];
1012
+ const current = typeof service?.current === "function" ? service.current(agent.session) : null;
1013
+ const options = catalog.slice(0, 12).map((option) => {
1014
+ const name = clipped(option?.value, 60);
1015
+ if (!name) return null;
1016
+ let spec = null;
1017
+ try {
1018
+ spec = typeof service?.specOf === "function" ? service.specOf(name) : null;
1019
+ } catch {
1020
+ spec = null;
1021
+ }
1022
+ return {
1023
+ name,
1024
+ label: clipped(option?.name, 80) || name,
1025
+ ...(option?.description ? { description: clipped(option.description, 300) } : {}),
1026
+ ...(spec?.sandbox ? { sandbox: clipped(spec.sandbox, 40) } : {}),
1027
+ ...(spec?.approval ? { approval: clipped(spec.approval, 40) } : {}),
1028
+ };
1029
+ }).filter(Boolean);
1030
+ return { current: clipped(current, 60) || null, options };
1031
+ }
1032
+
1033
+ /** Switch this conversation's permission preset, if the deployment exposes them. */
1034
+ async selectPermission(state, command) {
1035
+ const service = permissionServiceOf(this.ctx);
1036
+ if (typeof service?.set !== "function") {
1037
+ await this.reportCommandResult(state, command.requestId, {
1038
+ ok: false,
1039
+ error: "这个 DSH Desktop 版本没有提供权限预设(permissionPresets)",
1040
+ });
1041
+ return;
1042
+ }
1043
+ const name = clipped(command.name, 60);
1044
+ try {
1045
+ service.set(state.agent.session, name);
1046
+ const applied = typeof service.current === "function" ? service.current(state.agent.session) : name;
1047
+ await this.reportCommandResult(state, command.requestId, { ok: true, selected: applied });
1048
+ } catch (error) {
1049
+ await this.reportCommandResult(state, command.requestId, { ok: false, error: textFromError(error) });
1050
+ }
1051
+ }
1052
+
976
1053
  async modelDirectory(agent) {
977
1054
  const current = selectionFromAgent(agent);
978
1055
  try {
@@ -1155,31 +1232,94 @@ export class PhoneConnections {
1155
1232
  }
1156
1233
  }
1157
1234
 
1235
+ /**
1236
+ * One approval, from DSH's question to the phone's answer.
1237
+ *
1238
+ * Returns what DSH expects back from the hook: `allowed-once` is the only grant,
1239
+ * `rejected` the explicit refusal, `cancelled` when the chance expired or the turn
1240
+ * went away, and `unavailable` when there is no live phone channel to ask through —
1241
+ * in that case the desktop window owns the decision, exactly as before.
1242
+ */
1243
+ async approvalRequest(request) {
1244
+ const sessionId = request?.agent?.session?.id;
1245
+ const state = sessionId ? this.bySession.get(sessionId) : null;
1246
+ if (!state || state.controller.signal.aborted) return "unavailable";
1247
+
1248
+ const approvalId = randomUUID();
1249
+ const scope = this.#interactionScope(sessionId);
1250
+ scope.queue.push({
1251
+ kind: "approval-requested",
1252
+ requestId: approvalId,
1253
+ dshApprovalId: approvalId,
1254
+ toolName: clipped(request?.toolName, 200) || "tool",
1255
+ ...(request?.reason ? { reason: clipped(request.reason, 2_000) } : {}),
1256
+ ...(request?.callId ? { callId: clipped(request.callId, 200) } : {}),
1257
+ });
1258
+ void this.#drainInteractions(state, scope, sessionId);
1259
+
1260
+ const pending = this.approvalIds.get(sessionId) ?? new Set();
1261
+ pending.add(approvalId);
1262
+ this.approvalIds.set(sessionId, pending);
1263
+
1264
+ const outcome = await this.approvals.wait(approvalId, {
1265
+ signal: request?.signal ?? state.controller.signal,
1266
+ });
1267
+
1268
+ pending.delete(approvalId);
1269
+ if (pending.size === 0) this.approvalIds.delete(sessionId);
1270
+
1271
+ // Settle the card so it stops looking answerable, whichever way it ended.
1272
+ const live = this.bySession.get(sessionId);
1273
+ if (live && !live.controller.signal.aborted) {
1274
+ const settle = this.#interactionScope(sessionId);
1275
+ settle.queue.push({ kind: "approval-resolved", requestId: "", dshApprovalId: approvalId, outcome });
1276
+ void this.#drainInteractions(live, settle, sessionId);
1277
+ }
1278
+ return outcome;
1279
+ }
1280
+
1158
1281
  async answerApproval(state, command) {
1159
- const key = `${APPROVAL_PREFIX}${command.dshApprovalId}`;
1160
- state.answered.add(key);
1161
- try {
1162
- const receipt = await this.respond(command.rpcId, {
1163
- ok: true,
1164
- value: {
1165
- sessionId: state.agent.session.id,
1166
- approvalId: command.dshApprovalId,
1167
- outcome: command.outcome === "allowed-once" ? "allowed-once" : "rejected",
1168
- },
1169
- });
1170
- if (!receipt?.accepted) {
1171
- state.answered.delete(key);
1172
- await this.reportCommandResult(state, command.requestId, {
1173
- ok: false,
1174
- error: `DSH Desktop did not accept this decision (${receipt?.reason ?? "unknown"})`,
1282
+ const approvalId = String(command.dshApprovalId ?? "");
1283
+ // The normal path on DSH 0.2.x: the request is parked in the broker, waiting for
1284
+ // this decision to come back over the bridge.
1285
+ if (this.approvals.resolve(approvalId, command.outcome)) {
1286
+ await this.reportCommandResult(state, command.requestId, { ok: true });
1287
+ return;
1288
+ }
1289
+ // A card carried by the older rpc channel (a DSH build that still exposes the
1290
+ // client stream) is answered where it came from, so an upgraded phone still works
1291
+ // against an older desktop.
1292
+ if (command.rpcId) {
1293
+ const key = `${APPROVAL_PREFIX}${approvalId}`;
1294
+ state.answered.add(key);
1295
+ try {
1296
+ const receipt = await this.respond(command.rpcId, {
1297
+ ok: true,
1298
+ value: {
1299
+ sessionId: state.agent.session.id,
1300
+ approvalId,
1301
+ outcome: command.outcome === "allowed-once" ? "allowed-once" : "rejected",
1302
+ },
1175
1303
  });
1176
- return;
1304
+ if (!receipt?.accepted) {
1305
+ state.answered.delete(key);
1306
+ await this.reportCommandResult(state, command.requestId, {
1307
+ ok: false,
1308
+ error: `DSH Desktop did not accept this decision (${receipt?.reason ?? "unknown"})`,
1309
+ });
1310
+ return;
1311
+ }
1312
+ await this.reportCommandResult(state, command.requestId, { ok: true });
1313
+ } catch (error) {
1314
+ state.answered.delete(key);
1315
+ await this.reportCommandResult(state, command.requestId, { ok: false, error: textFromError(error) });
1177
1316
  }
1178
- await this.reportCommandResult(state, command.requestId, { ok: true });
1179
- } catch (error) {
1180
- state.answered.delete(key);
1181
- await this.reportCommandResult(state, command.requestId, { ok: false, error: textFromError(error) });
1317
+ return;
1182
1318
  }
1319
+ await this.reportCommandResult(state, command.requestId, {
1320
+ ok: false,
1321
+ error: "这张批准卡已经失效:可能已在桌面端处理,或已经超时",
1322
+ });
1183
1323
  }
1184
1324
 
1185
1325
  /** Tear the channel down; the conversation itself lives on (a reconnect reuses it). */
@@ -1189,6 +1329,9 @@ export class PhoneConnections {
1189
1329
  state.controller.abort();
1190
1330
  if (state.eventTimer) clearTimeout(state.eventTimer);
1191
1331
  this.bySession.delete(sessionId);
1332
+ // An approval card outlives the channel that carried it, but the question behind it
1333
+ // does not: leaving it pending would hold the tool call until the broker's timeout.
1334
+ this.#cancelApprovals(sessionId);
1192
1335
  }
1193
1336
 
1194
1337
  /** The desktop let go of the conversation: stop every loop, including reconnect. */
@@ -1201,6 +1344,14 @@ export class PhoneConnections {
1201
1344
  this.close(sessionId);
1202
1345
  }
1203
1346
 
1347
+ /** Settle every approval this conversation was waiting on as cancelled. */
1348
+ #cancelApprovals(sessionId) {
1349
+ const ids = this.approvalIds.get(sessionId);
1350
+ if (!ids?.size) return;
1351
+ this.approvalIds.delete(sessionId);
1352
+ for (const approvalId of ids) this.approvals.cancel(approvalId);
1353
+ }
1354
+
1204
1355
  captureEvent(session, event) {
1205
1356
  const state = this.bySession.get(session.id);
1206
1357
  if (!state || state.controller.signal.aborted) return;
@@ -1323,6 +1474,8 @@ export class PhoneConnections {
1323
1474
  }
1324
1475
  } else if (command.kind === "answer-question" || command.kind === "cancel-question") {
1325
1476
  await this.answerQuestion(state, command);
1477
+ } else if (command.kind === "select-permission") {
1478
+ await this.selectPermission(state, command);
1326
1479
  } else if (command.kind === "create-session") {
1327
1480
  await this.createSession(state, command);
1328
1481
  } else if (command.kind === "answer-approval") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chenacc/dsh-agentbridge",
3
- "version": "0.4.7",
3
+ "version": "0.4.9",
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/approval-broker.js",
13
14
  "cordis.patch.yml",
14
15
  "README.md",
15
16
  "LICENSE",