dsh-browser-firefox 0.4.7 → 0.5.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 CHANGED
@@ -6,6 +6,8 @@
6
6
 
7
7
  ## 安装
8
8
 
9
+ 需要 dsh **≥ 0.2.1-rc.5**;配套 Firefox 扩展需同为 **0.5.0**(否则侧边栏会出现版本横幅)。
10
+
9
11
  ```sh
10
12
  dsh plugin --profile web add dsh-browser-firefox@latest
11
13
  ```
package/cordis.patch.yml CHANGED
File without changes
package/lib/index.js CHANGED
@@ -6,6 +6,29 @@ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
6
6
  import { WebSocket, WebSocketServer } from "ws";
7
7
  import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
8
  import { dirname } from "node:path";
9
+ //#region lib/types/session-follow.js
10
+ /**
11
+ * Session id displayed by a `session/follow` stream, read from the host's
12
+ * `SessionFollowRequest.address`. A subagent address carries the child session
13
+ * on `childSessionId`; ownership then walks up to the parent conversation, so
14
+ * either form routes the card correctly.
15
+ *
16
+ * @param args - native args of the `stream.open` frame.
17
+ * @returns the followed session id, or undefined when absent/malformed.
18
+ */
19
+ function followedSessionOf(args) {
20
+ const request = args.request;
21
+ if (typeof request !== "object" || request === null || Array.isArray(request)) return void 0;
22
+ const address = request.address;
23
+ if (typeof address !== "object" || address === null || Array.isArray(address)) return void 0;
24
+ const fields = address;
25
+ if (fields.kind === "session") return nonEmptyString(fields.sessionId);
26
+ if (fields.kind === "subagent") return nonEmptyString(fields.childSessionId);
27
+ }
28
+ function nonEmptyString(value) {
29
+ return typeof value === "string" && value.length > 0 ? value : void 0;
30
+ }
31
+ //#endregion
9
32
  //#region lib/types/token.js
10
33
  /**
11
34
  * Bridge bearer-token lifecycle: generation, constant-time verification, and
@@ -166,10 +189,16 @@ function delay(ms) {
166
189
  /**
167
190
  * Race one promise against an abort signal. Resolves `undefined` when the
168
191
  * signal wins; the loser's handlers are always attached, so a late rejection
169
- * cannot surface as an unhandled rejection.
192
+ * cannot surface as an unhandled rejection — the host loader escalates those
193
+ * to a fatal load failure.
194
+ *
195
+ * Exported for tests.
170
196
  */
171
197
  function raceAbort(promise, signal) {
172
- if (signal.aborted) return Promise.resolve(void 0);
198
+ if (signal.aborted) {
199
+ promise.catch(() => void 0);
200
+ return Promise.resolve(void 0);
201
+ }
173
202
  return new Promise((resolve, reject) => {
174
203
  const onAbort = () => {
175
204
  resolve(void 0);
@@ -195,13 +224,6 @@ function orderedSessionId(frame) {
195
224
  const sessionId = request.sessionId;
196
225
  return typeof sessionId === "string" ? sessionId : void 0;
197
226
  }
198
- /** Session id carried by a `session/follow` stream's native args. */
199
- function followedSessionOf(args) {
200
- const request = args.request;
201
- if (typeof request !== "object" || request === null || Array.isArray(request)) return void 0;
202
- const sessionId = request.sessionId;
203
- return typeof sessionId === "string" && sessionId.length > 0 ? sessionId : void 0;
204
- }
205
227
  /** Loopback IPv4/IPv6 literals (IPv4-mapped included). Exported for tests and reuse. */
206
228
  function isLoopbackAddress(address) {
207
229
  return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
@@ -577,6 +599,7 @@ var BridgeServer = class {
577
599
  try {
578
600
  iterator = (await this.deps.openStream(frame.method, frame.args, abort.signal))[Symbol.asyncIterator]();
579
601
  for (;;) {
602
+ if (abort.signal.aborted) break;
580
603
  const next = await raceAbort(iterator.next(), abort.signal);
581
604
  if (next === void 0 || next.done === true) break;
582
605
  if (ws.readyState !== WebSocket.OPEN) break;
@@ -588,26 +611,32 @@ var BridgeServer = class {
588
611
  });
589
612
  }
590
613
  } catch (error) {
591
- if (!abort.signal.aborted && ws.readyState === WebSocket.OPEN) sendFrame(ws, {
592
- t: "stream.error",
593
- id: frame.id,
594
- message: String(error)
595
- });
614
+ if (!abort.signal.aborted && ws.readyState === WebSocket.OPEN) try {
615
+ sendFrame(ws, {
616
+ t: "stream.error",
617
+ id: frame.id,
618
+ message: String(error)
619
+ });
620
+ } catch {}
596
621
  } finally {
597
622
  if (iterator !== void 0) try {
598
623
  await iterator.return?.();
599
624
  } catch {}
600
625
  const current = this.current;
601
626
  if (current !== null && current.streams.get(frame.id)?.pump === pump) current.streams.delete(frame.id);
602
- if (followedSessionId !== void 0) this.deps.onFollowChanged?.(followedSessionId, false);
627
+ if (followedSessionId !== void 0) try {
628
+ this.deps.onFollowChanged?.(followedSessionId, false);
629
+ } catch {}
603
630
  }
604
631
  })();
605
632
  conn.streams.set(frame.id, {
606
633
  abort,
607
- pump,
608
- ...followedSessionId === void 0 ? {} : { followedSessionId }
634
+ pump
609
635
  });
610
- if (followedSessionId !== void 0) this.deps.onFollowChanged?.(followedSessionId, true);
636
+ pump.catch(() => {});
637
+ if (followedSessionId !== void 0) try {
638
+ this.deps.onFollowChanged?.(followedSessionId, true);
639
+ } catch {}
611
640
  }
612
641
  /**
613
642
  * Backpressure gate for stream pumps. Returns false when the wait ended
@@ -1264,6 +1293,46 @@ function withSessionWorkspace(dispatch, workspacePath, warn) {
1264
1293
  };
1265
1294
  }
1266
1295
  //#endregion
1296
+ //#region lib/types/gateway-peer.js
1297
+ /**
1298
+ * In-process owner Peer for Typert Remote dispatch.
1299
+ *
1300
+ * dsh 0.2.1 requires every `typertGateway.invoke` / `stream` request to name a
1301
+ * live {@link PeerScope}: the Gateway reads `peer.signal` and `peer.principal`
1302
+ * without a fallback, because the 0.2.0 operator-peer default is gone. The
1303
+ * bridge mounts its own token-authenticated carrier, so it speaks as the host
1304
+ * owner; the Peer lives exactly as long as the plugin fiber.
1305
+ *
1306
+ * @module
1307
+ */
1308
+ /**
1309
+ * Create the bridge's owner Peer and tie its lifetime to the calling fiber.
1310
+ *
1311
+ * The returned scope is structurally a full `PeerScope`; the Gateway only
1312
+ * needs `id`, `principal`, `signal`, and `interactions` for unary calls and
1313
+ * streams, while `ctx` keeps a future event-stream registration fiber-scoped.
1314
+ *
1315
+ * @param ctx - plugin context whose disposal aborts the peer.
1316
+ * @returns a live owner Peer that is aborted when the plugin unloads.
1317
+ */
1318
+ function createGatewayPeer(ctx) {
1319
+ const lifetime = new AbortController();
1320
+ const dispose = async () => {
1321
+ if (!lifetime.signal.aborted) lifetime.abort(/* @__PURE__ */ new Error("bridge-browser: gateway peer disposed"));
1322
+ };
1323
+ ctx.effect(() => () => {
1324
+ dispose();
1325
+ }, "bridge-browser: gateway peer");
1326
+ return {
1327
+ id: randomUUID(),
1328
+ ctx,
1329
+ principal: { kind: "owner" },
1330
+ signal: lifetime.signal,
1331
+ interactions: "none",
1332
+ dispose
1333
+ };
1334
+ }
1335
+ //#endregion
1267
1336
  //#region lib/types/extension-sessions.js
1268
1337
  /**
1269
1338
  * Track session ids that the browser extension has driven through the bridge.
@@ -1332,6 +1401,8 @@ var FollowedSessions = class {
1332
1401
  this.counts.clear();
1333
1402
  }
1334
1403
  };
1404
+ /** Maximum ancestor hops when looking for an owned session. */
1405
+ const MAX_OWNER_DEPTH = 8;
1335
1406
  /** Whether one exact session id is extension-owned by either source. */
1336
1407
  function isOwnedSession(sessionId, sources) {
1337
1408
  if (sessionId === void 0) return false;
@@ -1353,7 +1424,7 @@ function owningSessionId(sessionId, sources, parentOf) {
1353
1424
  if (parentOf === void 0) return void 0;
1354
1425
  const seen = /* @__PURE__ */ new Set([sessionId]);
1355
1426
  let current = sessionId;
1356
- for (let depth = 0; depth < 8; depth += 1) {
1427
+ for (let depth = 0; depth < MAX_OWNER_DEPTH; depth += 1) {
1357
1428
  const parent = parentOf(current);
1358
1429
  if (parent === void 0 || parent.length === 0 || seen.has(parent)) return void 0;
1359
1430
  if (isOwnedSession(parent, sources)) return parent;
@@ -1388,6 +1459,75 @@ function resolveInteractionOwnership(input) {
1388
1459
  };
1389
1460
  }
1390
1461
  //#endregion
1462
+ //#region lib/types/waterfall.js
1463
+ /**
1464
+ * Bookkeeping shared by the host waterfalls the bridge claims
1465
+ * (`user-questions/request`, `approval/request`).
1466
+ *
1467
+ * Both bridges need exactly the same lifecycle: one pending entry per
1468
+ * generated id, a **single settlement** guarantee against concurrent paths
1469
+ * (extension answer vs host abort vs connection loss vs plugin unload), an
1470
+ * abort listener that is detached once settled, and the id+session match the
1471
+ * uplink must pass before it may touch an entry. Only the outcome vocabulary
1472
+ * and the push/settle policy differ, and those stay in the domain modules.
1473
+ *
1474
+ * @module
1475
+ */
1476
+ /** Registry of pending waterfall requests, keyed by the id sent to the extension. */
1477
+ var PendingWaterfalls = class {
1478
+ entries = /* @__PURE__ */ new Map();
1479
+ /**
1480
+ * Track one request pushed to the extension.
1481
+ *
1482
+ * @param input - id, asking session, host cancellation signal, the domain's
1483
+ * settlement policy, and the abort handler (typically: tell the extension
1484
+ * the card is gone, then settle).
1485
+ */
1486
+ register(input) {
1487
+ const entry = {
1488
+ sessionId: input.sessionId,
1489
+ payload: input.payload,
1490
+ complete: input.complete,
1491
+ signal: input.signal,
1492
+ onAbort: input.onAbort,
1493
+ settled: false
1494
+ };
1495
+ if (input.signal !== void 0) input.signal.addEventListener("abort", input.onAbort, { once: true });
1496
+ this.entries.set(input.id, entry);
1497
+ }
1498
+ /**
1499
+ * Whether an unsettled entry exists for exactly this id and session. The
1500
+ * uplink must not be able to settle another session's card.
1501
+ */
1502
+ matches(id, sessionId) {
1503
+ const entry = this.entries.get(id);
1504
+ return entry !== void 0 && !entry.settled && entry.sessionId === sessionId;
1505
+ }
1506
+ /** Domain payload registered with one unsettled entry (undefined once settled). */
1507
+ payloadOf(id) {
1508
+ return this.entries.get(id)?.payload;
1509
+ }
1510
+ /**
1511
+ * Settle one request. Later settlements for the same id are no-ops, and the
1512
+ * entry is dropped together with its abort listener.
1513
+ *
1514
+ * @returns true when this call performed the settlement.
1515
+ */
1516
+ settle(id, outcome) {
1517
+ const entry = this.entries.get(id);
1518
+ if (entry === void 0 || entry.settled) return false;
1519
+ entry.settled = true;
1520
+ this.entries.delete(id);
1521
+ if (entry.onAbort !== void 0) entry.signal?.removeEventListener("abort", entry.onAbort);
1522
+ entry.complete(outcome);
1523
+ return true;
1524
+ }
1525
+ /** Every unsettled id, for the connection-loss and unload sweeps. */
1526
+ ids() {
1527
+ return [...this.entries.keys()];
1528
+ }
1529
+ };
1530
+ //#endregion
1391
1531
  //#region lib/types/questions.js
1392
1532
  /**
1393
1533
  * ask_user_question ownership: claim the host `user-questions/request`
@@ -1442,7 +1582,7 @@ function asQuestionAnswerArgs(value) {
1442
1582
  /** Owns the user-questions waterfall for extension-driven sessions. */
1443
1583
  var QuestionBridge = class {
1444
1584
  deps;
1445
- pending = /* @__PURE__ */ new Map();
1585
+ waterfalls = new PendingWaterfalls();
1446
1586
  constructor(deps) {
1447
1587
  this.deps = deps;
1448
1588
  }
@@ -1459,38 +1599,33 @@ var QuestionBridge = class {
1459
1599
  ask(sessionId, questions, next, signal) {
1460
1600
  if (signal?.aborted) return Promise.reject(abortedError());
1461
1601
  const questionId = randomUUID();
1602
+ const questionIds = new Set(questions.map((question) => question.id));
1462
1603
  return new Promise((resolve, reject) => {
1463
- const entry = {
1604
+ const settle = (outcome) => {
1605
+ this.waterfalls.settle(questionId, outcome);
1606
+ };
1607
+ this.waterfalls.register({
1608
+ id: questionId,
1464
1609
  sessionId,
1465
- questionIds: new Set(questions.map((question) => question.id)),
1466
- settled: false,
1467
1610
  signal,
1611
+ payload: questionIds,
1468
1612
  complete: (outcome) => {
1469
- if (entry.settled) return;
1470
- entry.settled = true;
1471
- this.pending.delete(questionId);
1472
- if (entry.onAbort !== void 0) entry.signal?.removeEventListener("abort", entry.onAbort);
1473
1613
  if (outcome.kind === "answer") resolve(outcome.answer);
1474
1614
  else if (outcome.kind === "reject") reject(outcome.error);
1475
1615
  else next().then(resolve, reject);
1476
1616
  },
1477
- onAbort: void 0
1478
- };
1479
- if (signal !== void 0) {
1480
- entry.onAbort = () => {
1617
+ onAbort: () => {
1481
1618
  this.deps.push({
1482
1619
  t: "question.resolved",
1483
1620
  id: questionId,
1484
1621
  sessionId
1485
1622
  });
1486
- entry.complete({
1623
+ settle({
1487
1624
  kind: "reject",
1488
1625
  error: abortedError()
1489
1626
  });
1490
- };
1491
- signal.addEventListener("abort", entry.onAbort, { once: true });
1492
- }
1493
- this.pending.set(questionId, entry);
1627
+ }
1628
+ });
1494
1629
  this.deps.push({
1495
1630
  t: "question.requested",
1496
1631
  id: questionId,
@@ -1504,24 +1639,23 @@ var QuestionBridge = class {
1504
1639
  * rpc. The server replies with this receipt.
1505
1640
  */
1506
1641
  answer(args) {
1507
- const entry = this.pending.get(args.questionId);
1508
- if (entry === void 0 || entry.settled || entry.sessionId !== args.sessionId) return {
1642
+ if (!this.waterfalls.matches(args.questionId, args.sessionId)) return {
1509
1643
  accepted: false,
1510
1644
  reason: "not-pending"
1511
1645
  };
1512
1646
  if (args.decline === true) {
1513
- entry.complete({
1647
+ this.waterfalls.settle(args.questionId, {
1514
1648
  kind: "reject",
1515
1649
  error: declinedError()
1516
1650
  });
1517
1651
  return { accepted: true };
1518
1652
  }
1519
- const answer = asAnswerPayload(args.answer, entry.questionIds);
1653
+ const answer = asAnswerPayload(args.answer, this.waterfalls.payloadOf(args.questionId) ?? /* @__PURE__ */ new Set());
1520
1654
  if (answer === void 0) return {
1521
1655
  accepted: false,
1522
1656
  reason: "bad-answer"
1523
1657
  };
1524
- entry.complete({
1658
+ this.waterfalls.settle(args.questionId, {
1525
1659
  kind: "answer",
1526
1660
  answer
1527
1661
  });
@@ -1529,11 +1663,11 @@ var QuestionBridge = class {
1529
1663
  }
1530
1664
  /** Bridge connection replaced/closed: delegate every unsettled question. */
1531
1665
  delegateAll() {
1532
- for (const entry of [...this.pending.values()]) if (!entry.settled) entry.complete({ kind: "delegate" });
1666
+ for (const id of this.waterfalls.ids()) this.waterfalls.settle(id, { kind: "delegate" });
1533
1667
  }
1534
1668
  /** Plugin unload: reject everything so no tool call outlives the plugin. */
1535
1669
  dispose() {
1536
- for (const entry of [...this.pending.values()]) if (!entry.settled) entry.complete({
1670
+ for (const id of this.waterfalls.ids()) this.waterfalls.settle(id, {
1537
1671
  kind: "reject",
1538
1672
  error: /* @__PURE__ */ new Error("browser bridge plugin was unloaded")
1539
1673
  });
@@ -1563,17 +1697,18 @@ function asApprovalDecisionArgs(value) {
1563
1697
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
1564
1698
  const args = value;
1565
1699
  if (typeof args.approvalId !== "string" || typeof args.sessionId !== "string") return void 0;
1566
- if (args.decision !== "allowed-once" && args.decision !== "rejected") return void 0;
1700
+ const decision = args.decision;
1701
+ if (decision !== "allowed-once" && decision !== "rejected") return void 0;
1567
1702
  return {
1568
1703
  approvalId: args.approvalId,
1569
1704
  sessionId: args.sessionId,
1570
- decision: args.decision
1705
+ decision
1571
1706
  };
1572
1707
  }
1573
1708
  /** Owns the host approval waterfall for extension-driven sessions. */
1574
1709
  var ApprovalBridge = class {
1575
1710
  deps;
1576
- pending = /* @__PURE__ */ new Map();
1711
+ waterfalls = new PendingWaterfalls();
1577
1712
  constructor(deps) {
1578
1713
  this.deps = deps;
1579
1714
  }
@@ -1591,35 +1726,27 @@ var ApprovalBridge = class {
1591
1726
  if (signal?.aborted) return Promise.resolve("cancelled");
1592
1727
  const approvalId = randomUUID();
1593
1728
  return new Promise((resolve, reject) => {
1594
- const entry = {
1729
+ this.waterfalls.register({
1730
+ id: approvalId,
1595
1731
  sessionId: routingSessionId,
1596
- settled: false,
1597
1732
  signal,
1733
+ payload: void 0,
1598
1734
  complete: (outcome) => {
1599
- if (entry.settled) return;
1600
- entry.settled = true;
1601
- this.pending.delete(approvalId);
1602
- if (entry.onAbort !== void 0) entry.signal?.removeEventListener("abort", entry.onAbort);
1603
1735
  if (outcome.kind === "decide") resolve(outcome.outcome);
1604
1736
  else next().then(resolve, reject);
1605
1737
  },
1606
- onAbort: void 0
1607
- };
1608
- if (signal !== void 0) {
1609
- entry.onAbort = () => {
1738
+ onAbort: () => {
1610
1739
  this.deps.push({
1611
1740
  t: "approval.resolved",
1612
1741
  id: approvalId,
1613
1742
  sessionId: routingSessionId
1614
1743
  });
1615
- entry.complete({
1744
+ this.waterfalls.settle(approvalId, {
1616
1745
  kind: "decide",
1617
1746
  outcome: "cancelled"
1618
1747
  });
1619
- };
1620
- signal.addEventListener("abort", entry.onAbort, { once: true });
1621
- }
1622
- this.pending.set(approvalId, entry);
1748
+ }
1749
+ });
1623
1750
  this.deps.push({
1624
1751
  t: "approval.requested",
1625
1752
  id: approvalId,
@@ -1635,8 +1762,7 @@ var ApprovalBridge = class {
1635
1762
  * rpc. The server replies with this receipt.
1636
1763
  */
1637
1764
  decide(args) {
1638
- const entry = this.pending.get(args.approvalId);
1639
- if (entry === void 0 || entry.settled || entry.sessionId !== args.sessionId) return {
1765
+ if (!this.waterfalls.matches(args.approvalId, args.sessionId)) return {
1640
1766
  accepted: false,
1641
1767
  reason: "not-pending"
1642
1768
  };
@@ -1644,7 +1770,7 @@ var ApprovalBridge = class {
1644
1770
  accepted: false,
1645
1771
  reason: "bad-decision"
1646
1772
  };
1647
- entry.complete({
1773
+ this.waterfalls.settle(args.approvalId, {
1648
1774
  kind: "decide",
1649
1775
  outcome: args.decision
1650
1776
  });
@@ -1652,11 +1778,11 @@ var ApprovalBridge = class {
1652
1778
  }
1653
1779
  /** Bridge connection replaced/closed: delegate every unsettled approval. */
1654
1780
  delegateAll() {
1655
- for (const entry of [...this.pending.values()]) if (!entry.settled) entry.complete({ kind: "delegate" });
1781
+ for (const id of this.waterfalls.ids()) this.waterfalls.settle(id, { kind: "delegate" });
1656
1782
  }
1657
1783
  /** Plugin unload: answer everything fail-closed so no tool call outlives the plugin. */
1658
1784
  dispose() {
1659
- for (const entry of [...this.pending.values()]) if (!entry.settled) entry.complete({
1785
+ for (const id of this.waterfalls.ids()) this.waterfalls.settle(id, {
1660
1786
  kind: "decide",
1661
1787
  outcome: "unavailable"
1662
1788
  });
@@ -1771,6 +1897,7 @@ function resolveConfig(config) {
1771
1897
  async function apply(ctx, config) {
1772
1898
  const resolved = resolveConfig(config);
1773
1899
  const tokenRes = await resolveToken(resolved.token);
1900
+ const peer = createGatewayPeer(ctx);
1774
1901
  const invoke = async (method, args, signal) => {
1775
1902
  const slash = method.indexOf("/");
1776
1903
  const namespace = slash === -1 ? method : method.slice(0, slash);
@@ -1782,7 +1909,8 @@ async function apply(ctx, config) {
1782
1909
  namespace,
1783
1910
  method: remoteMethod,
1784
1911
  args,
1785
- signal
1912
+ signal,
1913
+ peer
1786
1914
  })
1787
1915
  };
1788
1916
  } catch (error) {
@@ -1801,8 +1929,9 @@ async function apply(ctx, config) {
1801
1929
  driven: extensionSessions,
1802
1930
  followed: followedSessions
1803
1931
  };
1804
- const sessions = ctx.get("sessions");
1805
- const parentOf = sessions === void 0 ? void 0 : (sessionId) => sessions.get(sessionId)?.header.parentSession;
1932
+ const parentOf = (sessionId) => {
1933
+ return ctx.get("sessions")?.get(sessionId)?.header.parentSession;
1934
+ };
1806
1935
  const notingDispatchRpc = async (method, args, signal) => {
1807
1936
  const tracksOwnership = method === "session/create" || method === "session/prompt";
1808
1937
  const dispatched = tracksOwnership ? sessionIdOf(args.request) : void 0;
@@ -1840,7 +1969,8 @@ async function apply(ctx, config) {
1840
1969
  namespace,
1841
1970
  method: remoteMethod,
1842
1971
  args,
1843
- signal
1972
+ signal,
1973
+ peer
1844
1974
  });
1845
1975
  },
1846
1976
  answerQuestion: (args) => {
@@ -1876,7 +2006,9 @@ async function apply(ctx, config) {
1876
2006
  }
1877
2007
  });
1878
2008
  const logDelegation = (kind, sessionId, reason) => {
1879
- ctx.logger.info(`browser bridge: delegated ${kind} for session ${sessionId ?? "<unknown>"} (${reason})`);
2009
+ const line = `browser bridge: delegated ${kind} for session ${sessionId ?? "<unknown>"} (${reason})`;
2010
+ if (reason === "unsupported-client") ctx.logger.info(line);
2011
+ else ctx.logger.debug(line);
1880
2012
  };
1881
2013
  ctx.effect(() => {
1882
2014
  const disposeListener = ctx.on("user-questions/request", (request, next) => {
@@ -1885,7 +2017,7 @@ async function apply(ctx, config) {
1885
2017
  clientSupports: server.clientSupportsQuestions(),
1886
2018
  sessionId: request.agent?.id,
1887
2019
  sources: ownershipSources,
1888
- ...parentOf === void 0 ? {} : { parentOf }
2020
+ parentOf
1889
2021
  });
1890
2022
  if (!ownership.owned) {
1891
2023
  logDelegation("user-questions", request.agent?.id, ownership.reason);
@@ -1905,16 +2037,17 @@ async function apply(ctx, config) {
1905
2037
  clientSupports: server.clientSupportsApprovals(),
1906
2038
  sessionId: request.agent?.id,
1907
2039
  sources: ownershipSources,
1908
- ...parentOf === void 0 ? {} : { parentOf }
2040
+ parentOf
1909
2041
  });
1910
2042
  if (!ownership.owned) {
1911
2043
  logDelegation("approval", request.agent?.id, ownership.reason);
1912
2044
  return next();
1913
2045
  }
2046
+ const reason = approvalReasonText(request);
1914
2047
  return approvals.ask(ownership.sessionId, {
1915
2048
  toolName: request.toolName,
1916
2049
  ...typeof request.callId === "string" ? { callId: request.callId } : {},
1917
- ...approvalReasonText(request) === void 0 ? {} : { reason: approvalReasonText(request) }
2050
+ ...reason === void 0 ? {} : { reason }
1918
2051
  }, next, request.signal);
1919
2052
  }, { prepend: true });
1920
2053
  return () => {
package/lib/protocol.js CHANGED
File without changes
@@ -33,18 +33,18 @@ export type ApprovalReceipt = {
33
33
  accepted: false;
34
34
  reason: 'not-pending' | 'bad-decision';
35
35
  };
36
- /** Args of the plugin-local `bridge/approvalDecision` rpc method. */
36
+ /** Args of the plugin-local `bridge/approvalDecision` rpc method (decision already narrowed by the parser). */
37
37
  export interface ApprovalDecisionArgs {
38
38
  approvalId: string;
39
39
  sessionId: string;
40
- decision?: unknown;
40
+ decision: ApprovalDecision;
41
41
  }
42
42
  /** Parse the extension's `bridge/approvalDecision` rpc args (ids + closed decision). */
43
43
  export declare function asApprovalDecisionArgs(value: unknown): ApprovalDecisionArgs | undefined;
44
44
  /** Owns the host approval waterfall for extension-driven sessions. */
45
45
  export declare class ApprovalBridge {
46
46
  private readonly deps;
47
- private readonly pending;
47
+ private readonly waterfalls;
48
48
  constructor(deps: {
49
49
  /** Push one server frame to the connected extension (must tolerate a dead socket). */
50
50
  push: (frame: ServerFrame) => void;
@@ -51,8 +51,6 @@ export interface OwnershipSources {
51
51
  /** Sessions an open follow stream is displaying. */
52
52
  followed?: Pick<FollowedSessions, 'has'>;
53
53
  }
54
- /** Maximum ancestor hops when looking for an owned session. */
55
- export declare const MAX_OWNER_DEPTH = 8;
56
54
  /** Whether one exact session id is extension-owned by either source. */
57
55
  export declare function isOwnedSession(sessionId: string | undefined, sources: OwnershipSources): boolean;
58
56
  /**
@@ -90,14 +88,4 @@ export declare function resolveInteractionOwnership(input: {
90
88
  sources: OwnershipSources;
91
89
  parentOf?: (sessionId: string) => string | undefined;
92
90
  }): InteractionOwnership;
93
- /**
94
- * Decide whether the bridge should own ask_user_question for this request.
95
- * Thin compatibility wrapper over {@link resolveInteractionOwnership}.
96
- */
97
- export declare function shouldBridgeOwnQuestion(input: {
98
- hasExtensionConnection: boolean;
99
- clientSupportsQuestions: boolean;
100
- sessionId: string | undefined;
101
- extensionSessions: Pick<ExtensionSessionRegistry, 'has'>;
102
- }): boolean;
103
91
  //# sourceMappingURL=extension-sessions.d.ts.map
@@ -0,0 +1,27 @@
1
+ /**
2
+ * In-process owner Peer for Typert Remote dispatch.
3
+ *
4
+ * dsh 0.2.1 requires every `typertGateway.invoke` / `stream` request to name a
5
+ * live {@link PeerScope}: the Gateway reads `peer.signal` and `peer.principal`
6
+ * without a fallback, because the 0.2.0 operator-peer default is gone. The
7
+ * bridge mounts its own token-authenticated carrier, so it speaks as the host
8
+ * owner; the Peer lives exactly as long as the plugin fiber.
9
+ *
10
+ * @module
11
+ */
12
+ import type { Context } from '@deepseek-ai/cordis';
13
+ import type { InvokeRemoteRequest } from '@deepseek-ai/dsh-api-gateway/types';
14
+ /** The Peer a Gateway request must name (required since dsh 0.2.1). */
15
+ export type GatewayPeer = InvokeRemoteRequest['peer'];
16
+ /**
17
+ * Create the bridge's owner Peer and tie its lifetime to the calling fiber.
18
+ *
19
+ * The returned scope is structurally a full `PeerScope`; the Gateway only
20
+ * needs `id`, `principal`, `signal`, and `interactions` for unary calls and
21
+ * streams, while `ctx` keeps a future event-stream registration fiber-scoped.
22
+ *
23
+ * @param ctx - plugin context whose disposal aborts the peer.
24
+ * @returns a live owner Peer that is aborted when the plugin unloads.
25
+ */
26
+ export declare function createGatewayPeer(ctx: Context): GatewayPeer;
27
+ //# sourceMappingURL=gateway-peer.d.ts.map
File without changes
File without changes
@@ -47,7 +47,7 @@ export declare function asQuestionAnswerArgs(value: unknown): QuestionAnswerArgs
47
47
  /** Owns the user-questions waterfall for extension-driven sessions. */
48
48
  export declare class QuestionBridge {
49
49
  private readonly deps;
50
- private readonly pending;
50
+ private readonly waterfalls;
51
51
  constructor(deps: {
52
52
  /** Push one server frame to the connected extension (must tolerate a dead socket). */
53
53
  push: (frame: ServerFrame) => void;
@@ -31,6 +31,15 @@ import { type BridgeCaps, type RemoteWireResult, type ServerFrame, type ToolErro
31
31
  * same commit.
32
32
  */
33
33
  export declare const PRIVILEGED_METHODS: Set<string>;
34
+ /**
35
+ * Race one promise against an abort signal. Resolves `undefined` when the
36
+ * signal wins; the loser's handlers are always attached, so a late rejection
37
+ * cannot surface as an unhandled rejection — the host loader escalates those
38
+ * to a fatal load failure.
39
+ *
40
+ * Exported for tests.
41
+ */
42
+ export declare function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T | undefined>;
34
43
  /** Loopback IPv4/IPv6 literals (IPv4-mapped included). Exported for tests and reuse. */
35
44
  export declare function isLoopbackAddress(address: string | undefined): boolean;
36
45
  /** Error thrown by requestTool; the tool registry turns it into an isError result. */
File without changes