dsh-browser-firefox 0.4.7 → 0.4.8

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/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
@@ -1332,6 +1361,8 @@ var FollowedSessions = class {
1332
1361
  this.counts.clear();
1333
1362
  }
1334
1363
  };
1364
+ /** Maximum ancestor hops when looking for an owned session. */
1365
+ const MAX_OWNER_DEPTH = 8;
1335
1366
  /** Whether one exact session id is extension-owned by either source. */
1336
1367
  function isOwnedSession(sessionId, sources) {
1337
1368
  if (sessionId === void 0) return false;
@@ -1353,7 +1384,7 @@ function owningSessionId(sessionId, sources, parentOf) {
1353
1384
  if (parentOf === void 0) return void 0;
1354
1385
  const seen = /* @__PURE__ */ new Set([sessionId]);
1355
1386
  let current = sessionId;
1356
- for (let depth = 0; depth < 8; depth += 1) {
1387
+ for (let depth = 0; depth < MAX_OWNER_DEPTH; depth += 1) {
1357
1388
  const parent = parentOf(current);
1358
1389
  if (parent === void 0 || parent.length === 0 || seen.has(parent)) return void 0;
1359
1390
  if (isOwnedSession(parent, sources)) return parent;
@@ -1388,6 +1419,75 @@ function resolveInteractionOwnership(input) {
1388
1419
  };
1389
1420
  }
1390
1421
  //#endregion
1422
+ //#region lib/types/waterfall.js
1423
+ /**
1424
+ * Bookkeeping shared by the host waterfalls the bridge claims
1425
+ * (`user-questions/request`, `approval/request`).
1426
+ *
1427
+ * Both bridges need exactly the same lifecycle: one pending entry per
1428
+ * generated id, a **single settlement** guarantee against concurrent paths
1429
+ * (extension answer vs host abort vs connection loss vs plugin unload), an
1430
+ * abort listener that is detached once settled, and the id+session match the
1431
+ * uplink must pass before it may touch an entry. Only the outcome vocabulary
1432
+ * and the push/settle policy differ, and those stay in the domain modules.
1433
+ *
1434
+ * @module
1435
+ */
1436
+ /** Registry of pending waterfall requests, keyed by the id sent to the extension. */
1437
+ var PendingWaterfalls = class {
1438
+ entries = /* @__PURE__ */ new Map();
1439
+ /**
1440
+ * Track one request pushed to the extension.
1441
+ *
1442
+ * @param input - id, asking session, host cancellation signal, the domain's
1443
+ * settlement policy, and the abort handler (typically: tell the extension
1444
+ * the card is gone, then settle).
1445
+ */
1446
+ register(input) {
1447
+ const entry = {
1448
+ sessionId: input.sessionId,
1449
+ payload: input.payload,
1450
+ complete: input.complete,
1451
+ signal: input.signal,
1452
+ onAbort: input.onAbort,
1453
+ settled: false
1454
+ };
1455
+ if (input.signal !== void 0) input.signal.addEventListener("abort", input.onAbort, { once: true });
1456
+ this.entries.set(input.id, entry);
1457
+ }
1458
+ /**
1459
+ * Whether an unsettled entry exists for exactly this id and session. The
1460
+ * uplink must not be able to settle another session's card.
1461
+ */
1462
+ matches(id, sessionId) {
1463
+ const entry = this.entries.get(id);
1464
+ return entry !== void 0 && !entry.settled && entry.sessionId === sessionId;
1465
+ }
1466
+ /** Domain payload registered with one unsettled entry (undefined once settled). */
1467
+ payloadOf(id) {
1468
+ return this.entries.get(id)?.payload;
1469
+ }
1470
+ /**
1471
+ * Settle one request. Later settlements for the same id are no-ops, and the
1472
+ * entry is dropped together with its abort listener.
1473
+ *
1474
+ * @returns true when this call performed the settlement.
1475
+ */
1476
+ settle(id, outcome) {
1477
+ const entry = this.entries.get(id);
1478
+ if (entry === void 0 || entry.settled) return false;
1479
+ entry.settled = true;
1480
+ this.entries.delete(id);
1481
+ if (entry.onAbort !== void 0) entry.signal?.removeEventListener("abort", entry.onAbort);
1482
+ entry.complete(outcome);
1483
+ return true;
1484
+ }
1485
+ /** Every unsettled id, for the connection-loss and unload sweeps. */
1486
+ ids() {
1487
+ return [...this.entries.keys()];
1488
+ }
1489
+ };
1490
+ //#endregion
1391
1491
  //#region lib/types/questions.js
1392
1492
  /**
1393
1493
  * ask_user_question ownership: claim the host `user-questions/request`
@@ -1442,7 +1542,7 @@ function asQuestionAnswerArgs(value) {
1442
1542
  /** Owns the user-questions waterfall for extension-driven sessions. */
1443
1543
  var QuestionBridge = class {
1444
1544
  deps;
1445
- pending = /* @__PURE__ */ new Map();
1545
+ waterfalls = new PendingWaterfalls();
1446
1546
  constructor(deps) {
1447
1547
  this.deps = deps;
1448
1548
  }
@@ -1459,38 +1559,33 @@ var QuestionBridge = class {
1459
1559
  ask(sessionId, questions, next, signal) {
1460
1560
  if (signal?.aborted) return Promise.reject(abortedError());
1461
1561
  const questionId = randomUUID();
1562
+ const questionIds = new Set(questions.map((question) => question.id));
1462
1563
  return new Promise((resolve, reject) => {
1463
- const entry = {
1564
+ const settle = (outcome) => {
1565
+ this.waterfalls.settle(questionId, outcome);
1566
+ };
1567
+ this.waterfalls.register({
1568
+ id: questionId,
1464
1569
  sessionId,
1465
- questionIds: new Set(questions.map((question) => question.id)),
1466
- settled: false,
1467
1570
  signal,
1571
+ payload: questionIds,
1468
1572
  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
1573
  if (outcome.kind === "answer") resolve(outcome.answer);
1474
1574
  else if (outcome.kind === "reject") reject(outcome.error);
1475
1575
  else next().then(resolve, reject);
1476
1576
  },
1477
- onAbort: void 0
1478
- };
1479
- if (signal !== void 0) {
1480
- entry.onAbort = () => {
1577
+ onAbort: () => {
1481
1578
  this.deps.push({
1482
1579
  t: "question.resolved",
1483
1580
  id: questionId,
1484
1581
  sessionId
1485
1582
  });
1486
- entry.complete({
1583
+ settle({
1487
1584
  kind: "reject",
1488
1585
  error: abortedError()
1489
1586
  });
1490
- };
1491
- signal.addEventListener("abort", entry.onAbort, { once: true });
1492
- }
1493
- this.pending.set(questionId, entry);
1587
+ }
1588
+ });
1494
1589
  this.deps.push({
1495
1590
  t: "question.requested",
1496
1591
  id: questionId,
@@ -1504,24 +1599,23 @@ var QuestionBridge = class {
1504
1599
  * rpc. The server replies with this receipt.
1505
1600
  */
1506
1601
  answer(args) {
1507
- const entry = this.pending.get(args.questionId);
1508
- if (entry === void 0 || entry.settled || entry.sessionId !== args.sessionId) return {
1602
+ if (!this.waterfalls.matches(args.questionId, args.sessionId)) return {
1509
1603
  accepted: false,
1510
1604
  reason: "not-pending"
1511
1605
  };
1512
1606
  if (args.decline === true) {
1513
- entry.complete({
1607
+ this.waterfalls.settle(args.questionId, {
1514
1608
  kind: "reject",
1515
1609
  error: declinedError()
1516
1610
  });
1517
1611
  return { accepted: true };
1518
1612
  }
1519
- const answer = asAnswerPayload(args.answer, entry.questionIds);
1613
+ const answer = asAnswerPayload(args.answer, this.waterfalls.payloadOf(args.questionId) ?? /* @__PURE__ */ new Set());
1520
1614
  if (answer === void 0) return {
1521
1615
  accepted: false,
1522
1616
  reason: "bad-answer"
1523
1617
  };
1524
- entry.complete({
1618
+ this.waterfalls.settle(args.questionId, {
1525
1619
  kind: "answer",
1526
1620
  answer
1527
1621
  });
@@ -1529,11 +1623,11 @@ var QuestionBridge = class {
1529
1623
  }
1530
1624
  /** Bridge connection replaced/closed: delegate every unsettled question. */
1531
1625
  delegateAll() {
1532
- for (const entry of [...this.pending.values()]) if (!entry.settled) entry.complete({ kind: "delegate" });
1626
+ for (const id of this.waterfalls.ids()) this.waterfalls.settle(id, { kind: "delegate" });
1533
1627
  }
1534
1628
  /** Plugin unload: reject everything so no tool call outlives the plugin. */
1535
1629
  dispose() {
1536
- for (const entry of [...this.pending.values()]) if (!entry.settled) entry.complete({
1630
+ for (const id of this.waterfalls.ids()) this.waterfalls.settle(id, {
1537
1631
  kind: "reject",
1538
1632
  error: /* @__PURE__ */ new Error("browser bridge plugin was unloaded")
1539
1633
  });
@@ -1563,17 +1657,18 @@ function asApprovalDecisionArgs(value) {
1563
1657
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
1564
1658
  const args = value;
1565
1659
  if (typeof args.approvalId !== "string" || typeof args.sessionId !== "string") return void 0;
1566
- if (args.decision !== "allowed-once" && args.decision !== "rejected") return void 0;
1660
+ const decision = args.decision;
1661
+ if (decision !== "allowed-once" && decision !== "rejected") return void 0;
1567
1662
  return {
1568
1663
  approvalId: args.approvalId,
1569
1664
  sessionId: args.sessionId,
1570
- decision: args.decision
1665
+ decision
1571
1666
  };
1572
1667
  }
1573
1668
  /** Owns the host approval waterfall for extension-driven sessions. */
1574
1669
  var ApprovalBridge = class {
1575
1670
  deps;
1576
- pending = /* @__PURE__ */ new Map();
1671
+ waterfalls = new PendingWaterfalls();
1577
1672
  constructor(deps) {
1578
1673
  this.deps = deps;
1579
1674
  }
@@ -1591,35 +1686,27 @@ var ApprovalBridge = class {
1591
1686
  if (signal?.aborted) return Promise.resolve("cancelled");
1592
1687
  const approvalId = randomUUID();
1593
1688
  return new Promise((resolve, reject) => {
1594
- const entry = {
1689
+ this.waterfalls.register({
1690
+ id: approvalId,
1595
1691
  sessionId: routingSessionId,
1596
- settled: false,
1597
1692
  signal,
1693
+ payload: void 0,
1598
1694
  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
1695
  if (outcome.kind === "decide") resolve(outcome.outcome);
1604
1696
  else next().then(resolve, reject);
1605
1697
  },
1606
- onAbort: void 0
1607
- };
1608
- if (signal !== void 0) {
1609
- entry.onAbort = () => {
1698
+ onAbort: () => {
1610
1699
  this.deps.push({
1611
1700
  t: "approval.resolved",
1612
1701
  id: approvalId,
1613
1702
  sessionId: routingSessionId
1614
1703
  });
1615
- entry.complete({
1704
+ this.waterfalls.settle(approvalId, {
1616
1705
  kind: "decide",
1617
1706
  outcome: "cancelled"
1618
1707
  });
1619
- };
1620
- signal.addEventListener("abort", entry.onAbort, { once: true });
1621
- }
1622
- this.pending.set(approvalId, entry);
1708
+ }
1709
+ });
1623
1710
  this.deps.push({
1624
1711
  t: "approval.requested",
1625
1712
  id: approvalId,
@@ -1635,8 +1722,7 @@ var ApprovalBridge = class {
1635
1722
  * rpc. The server replies with this receipt.
1636
1723
  */
1637
1724
  decide(args) {
1638
- const entry = this.pending.get(args.approvalId);
1639
- if (entry === void 0 || entry.settled || entry.sessionId !== args.sessionId) return {
1725
+ if (!this.waterfalls.matches(args.approvalId, args.sessionId)) return {
1640
1726
  accepted: false,
1641
1727
  reason: "not-pending"
1642
1728
  };
@@ -1644,7 +1730,7 @@ var ApprovalBridge = class {
1644
1730
  accepted: false,
1645
1731
  reason: "bad-decision"
1646
1732
  };
1647
- entry.complete({
1733
+ this.waterfalls.settle(args.approvalId, {
1648
1734
  kind: "decide",
1649
1735
  outcome: args.decision
1650
1736
  });
@@ -1652,11 +1738,11 @@ var ApprovalBridge = class {
1652
1738
  }
1653
1739
  /** Bridge connection replaced/closed: delegate every unsettled approval. */
1654
1740
  delegateAll() {
1655
- for (const entry of [...this.pending.values()]) if (!entry.settled) entry.complete({ kind: "delegate" });
1741
+ for (const id of this.waterfalls.ids()) this.waterfalls.settle(id, { kind: "delegate" });
1656
1742
  }
1657
1743
  /** Plugin unload: answer everything fail-closed so no tool call outlives the plugin. */
1658
1744
  dispose() {
1659
- for (const entry of [...this.pending.values()]) if (!entry.settled) entry.complete({
1745
+ for (const id of this.waterfalls.ids()) this.waterfalls.settle(id, {
1660
1746
  kind: "decide",
1661
1747
  outcome: "unavailable"
1662
1748
  });
@@ -1801,8 +1887,9 @@ async function apply(ctx, config) {
1801
1887
  driven: extensionSessions,
1802
1888
  followed: followedSessions
1803
1889
  };
1804
- const sessions = ctx.get("sessions");
1805
- const parentOf = sessions === void 0 ? void 0 : (sessionId) => sessions.get(sessionId)?.header.parentSession;
1890
+ const parentOf = (sessionId) => {
1891
+ return ctx.get("sessions")?.get(sessionId)?.header.parentSession;
1892
+ };
1806
1893
  const notingDispatchRpc = async (method, args, signal) => {
1807
1894
  const tracksOwnership = method === "session/create" || method === "session/prompt";
1808
1895
  const dispatched = tracksOwnership ? sessionIdOf(args.request) : void 0;
@@ -1876,7 +1963,9 @@ async function apply(ctx, config) {
1876
1963
  }
1877
1964
  });
1878
1965
  const logDelegation = (kind, sessionId, reason) => {
1879
- ctx.logger.info(`browser bridge: delegated ${kind} for session ${sessionId ?? "<unknown>"} (${reason})`);
1966
+ const line = `browser bridge: delegated ${kind} for session ${sessionId ?? "<unknown>"} (${reason})`;
1967
+ if (reason === "unsupported-client") ctx.logger.info(line);
1968
+ else ctx.logger.debug(line);
1880
1969
  };
1881
1970
  ctx.effect(() => {
1882
1971
  const disposeListener = ctx.on("user-questions/request", (request, next) => {
@@ -1885,7 +1974,7 @@ async function apply(ctx, config) {
1885
1974
  clientSupports: server.clientSupportsQuestions(),
1886
1975
  sessionId: request.agent?.id,
1887
1976
  sources: ownershipSources,
1888
- ...parentOf === void 0 ? {} : { parentOf }
1977
+ parentOf
1889
1978
  });
1890
1979
  if (!ownership.owned) {
1891
1980
  logDelegation("user-questions", request.agent?.id, ownership.reason);
@@ -1905,16 +1994,17 @@ async function apply(ctx, config) {
1905
1994
  clientSupports: server.clientSupportsApprovals(),
1906
1995
  sessionId: request.agent?.id,
1907
1996
  sources: ownershipSources,
1908
- ...parentOf === void 0 ? {} : { parentOf }
1997
+ parentOf
1909
1998
  });
1910
1999
  if (!ownership.owned) {
1911
2000
  logDelegation("approval", request.agent?.id, ownership.reason);
1912
2001
  return next();
1913
2002
  }
2003
+ const reason = approvalReasonText(request);
1914
2004
  return approvals.ask(ownership.sessionId, {
1915
2005
  toolName: request.toolName,
1916
2006
  ...typeof request.callId === "string" ? { callId: request.callId } : {},
1917
- ...approvalReasonText(request) === void 0 ? {} : { reason: approvalReasonText(request) }
2007
+ ...reason === void 0 ? {} : { reason }
1918
2008
  }, next, request.signal);
1919
2009
  }, { prepend: true });
1920
2010
  return () => {
@@ -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
@@ -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. */
@@ -0,0 +1,46 @@
1
+ /**
2
+ * `session/follow` 的参数形状:宿主描述符要求
3
+ * `{request: {address: SessionAddress}}`,其中 address 是
4
+ * `{kind:'session', sessionId}` 或
5
+ * `{kind:'subagent', parentSessionId, childSessionId, mode}`。
6
+ *
7
+ * 扩展用 {@link sessionFollowArgs} 构造订阅参数,插件用
8
+ * {@link followedSessionOf} 从原生 args 里取回「正在展示哪个会话」。两者
9
+ * 同处一个模块,是为了让形状只有**一个**真实来源:0.4.7 曾因插件侧测试用
10
+ * 臆造形状(`request.sessionId`)而没发现 follow 归属在生产环境从未生效。
11
+ *
12
+ * @module @deepseek-ai/dsh-bridge-browser/src/session-follow
13
+ */
14
+ /** 普通会话的 follow 地址。 */
15
+ export interface SessionFollowAddress {
16
+ kind: 'session';
17
+ sessionId: string;
18
+ }
19
+ /** 直接 subagent 子会话的 follow 地址(宿主 SessionAddress 的另一形态)。 */
20
+ export interface SubagentFollowAddress {
21
+ kind: 'subagent';
22
+ parentSessionId: string;
23
+ childSessionId: string;
24
+ mode: 'one-shot' | 'continuable' | 'unknown';
25
+ }
26
+ /** 一次性订阅参数(`stream.open` 的 args)。 */
27
+ export interface SessionFollowArgs {
28
+ request: {
29
+ address: SessionFollowAddress | SubagentFollowAddress;
30
+ };
31
+ }
32
+ /** 订阅一个普通会话(面板当前会话始终用这一形态)。 */
33
+ export declare function sessionFollowArgs(sessionId: string): SessionFollowArgs;
34
+ /** 订阅一个 direct subagent 子会话(预留:目前面板不展示子会话)。 */
35
+ export declare function subagentFollowArgs(parentSessionId: string, childSessionId: string, mode?: SubagentFollowAddress['mode']): SessionFollowArgs;
36
+ /**
37
+ * Session id displayed by a `session/follow` stream, read from the host's
38
+ * `SessionFollowRequest.address`. A subagent address carries the child session
39
+ * on `childSessionId`; ownership then walks up to the parent conversation, so
40
+ * either form routes the card correctly.
41
+ *
42
+ * @param args - native args of the `stream.open` frame.
43
+ * @returns the followed session id, or undefined when absent/malformed.
44
+ */
45
+ export declare function followedSessionOf(args: Record<string, unknown>): string | undefined;
46
+ //# sourceMappingURL=session-follow.d.ts.map
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Bookkeeping shared by the host waterfalls the bridge claims
3
+ * (`user-questions/request`, `approval/request`).
4
+ *
5
+ * Both bridges need exactly the same lifecycle: one pending entry per
6
+ * generated id, a **single settlement** guarantee against concurrent paths
7
+ * (extension answer vs host abort vs connection loss vs plugin unload), an
8
+ * abort listener that is detached once settled, and the id+session match the
9
+ * uplink must pass before it may touch an entry. Only the outcome vocabulary
10
+ * and the push/settle policy differ, and those stay in the domain modules.
11
+ *
12
+ * @module
13
+ */
14
+ /** Registry of pending waterfall requests, keyed by the id sent to the extension. */
15
+ export declare class PendingWaterfalls<TOutcome, TPayload = undefined> {
16
+ private readonly entries;
17
+ /**
18
+ * Track one request pushed to the extension.
19
+ *
20
+ * @param input - id, asking session, host cancellation signal, the domain's
21
+ * settlement policy, and the abort handler (typically: tell the extension
22
+ * the card is gone, then settle).
23
+ */
24
+ register(input: {
25
+ id: string;
26
+ sessionId: string;
27
+ signal: AbortSignal | undefined;
28
+ payload: TPayload;
29
+ complete: (outcome: TOutcome) => void;
30
+ onAbort: () => void;
31
+ }): void;
32
+ /**
33
+ * Whether an unsettled entry exists for exactly this id and session. The
34
+ * uplink must not be able to settle another session's card.
35
+ */
36
+ matches(id: string, sessionId: string): boolean;
37
+ /** Domain payload registered with one unsettled entry (undefined once settled). */
38
+ payloadOf(id: string): TPayload | undefined;
39
+ /**
40
+ * Settle one request. Later settlements for the same id are no-ops, and the
41
+ * entry is dropped together with its abort listener.
42
+ *
43
+ * @returns true when this call performed the settlement.
44
+ */
45
+ settle(id: string, outcome: TOutcome): boolean;
46
+ /** Every unsettled id, for the connection-loss and unload sweeps. */
47
+ ids(): string[];
48
+ }
49
+ //# sourceMappingURL=waterfall.d.ts.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-browser-firefox",
3
3
  "description": "Firefox browser control for DeepSeek Harness: token-authenticated WebSocket bridge + browser_* tools (native-image screenshots) driving the user's own Firefox via the companion AMO extension, with sidebar ask_user_question answering",
4
- "version": "0.4.7",
4
+ "version": "0.4.8",
5
5
  "author": "tuojc",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -79,24 +79,17 @@
79
79
  "@deepseek-ai/cordis": "4.0.4",
80
80
  "@deepseek-ai/cordis-plugin-include": "1.0.9",
81
81
  "@deepseek-ai/cordis-plugin-loader": "1.0.5",
82
- "@deepseek-ai/dsh-agent": "0.2.0-rc.1",
83
- "@deepseek-ai/dsh-agent-loop": "0.2.0-rc.1",
84
82
  "@deepseek-ai/dsh-api-gateway": "0.2.0-rc.1",
85
83
  "@deepseek-ai/dsh-api-session-controller": "0.2.0-rc.1",
86
84
  "@deepseek-ai/dsh-api-workspace-controller": "0.2.0-rc.1",
87
85
  "@deepseek-ai/dsh-attachment": "0.2.0-rc.1",
88
86
  "@deepseek-ai/dsh-host-webserver": "0.2.0-rc.1",
89
87
  "@deepseek-ai/dsh-invariants": "0.2.0-rc.1",
90
- "@deepseek-ai/dsh-llm": "0.2.0-rc.1",
91
88
  "@deepseek-ai/dsh-home-paths": "0.2.0-rc.1",
92
89
  "@deepseek-ai/dsh-session": "0.2.0-rc.1",
93
- "@deepseek-ai/dsh-storage": "0.2.0-rc.1",
94
- "@deepseek-ai/dsh-storage-domain": "0.2.0-rc.1",
95
- "@deepseek-ai/dsh-storage-json": "0.2.0-rc.1",
96
90
  "@deepseek-ai/dsh-system-prompt": "0.2.0-rc.1",
97
91
  "@deepseek-ai/dsh-tools": "0.2.0-rc.1",
98
92
  "@deepseek-ai/dsh-user-questions": "0.2.0-rc.1",
99
- "@deepseek-ai/dsh-workspace": "0.2.0-rc.1",
100
93
  "@types/node": "^22.20.0",
101
94
  "@types/ws": "^8.18.1",
102
95
  "playwright-core": "^1.61.1",
package/src/approvals.ts CHANGED
@@ -18,6 +18,7 @@
18
18
 
19
19
  import { randomUUID } from 'node:crypto'
20
20
  import type { ServerFrame } from './protocol.ts'
21
+ import { PendingWaterfalls } from './waterfall.ts'
21
22
 
22
23
  /** The host's closed approval outcome vocabulary. */
23
24
  export type ApprovalOutcome = 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable'
@@ -37,37 +38,30 @@ export type ApprovalReceipt =
37
38
  | { accepted: true }
38
39
  | { accepted: false; reason: 'not-pending' | 'bad-decision' }
39
40
 
40
- /** Args of the plugin-local `bridge/approvalDecision` rpc method. */
41
+ /** Args of the plugin-local `bridge/approvalDecision` rpc method (decision already narrowed by the parser). */
41
42
  export interface ApprovalDecisionArgs {
42
43
  approvalId: string
43
44
  sessionId: string
44
- decision?: unknown
45
+ decision: ApprovalDecision
45
46
  }
46
47
 
47
48
  type PendingOutcome =
48
49
  | { kind: 'decide'; outcome: ApprovalOutcome }
49
50
  | { kind: 'delegate' }
50
51
 
51
- interface PendingApproval {
52
- readonly sessionId: string
53
- settled: boolean
54
- readonly complete: (outcome: PendingOutcome) => void
55
- readonly signal: AbortSignal | undefined
56
- onAbort: (() => void) | undefined
57
- }
58
-
59
52
  /** Parse the extension's `bridge/approvalDecision` rpc args (ids + closed decision). */
60
53
  export function asApprovalDecisionArgs(value: unknown): ApprovalDecisionArgs | undefined {
61
54
  if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
62
55
  const args = value as Record<string, unknown>
63
56
  if (typeof args.approvalId !== 'string' || typeof args.sessionId !== 'string') return undefined
64
- if (args.decision !== 'allowed-once' && args.decision !== 'rejected') return undefined
65
- return { approvalId: args.approvalId, sessionId: args.sessionId, decision: args.decision }
57
+ const decision = args.decision
58
+ if (decision !== 'allowed-once' && decision !== 'rejected') return undefined
59
+ return { approvalId: args.approvalId, sessionId: args.sessionId, decision }
66
60
  }
67
61
 
68
62
  /** Owns the host approval waterfall for extension-driven sessions. */
69
63
  export class ApprovalBridge {
70
- private readonly pending = new Map<string, PendingApproval>()
64
+ private readonly waterfalls = new PendingWaterfalls<PendingOutcome>()
71
65
 
72
66
  constructor(private readonly deps: {
73
67
  /** Push one server frame to the connected extension (must tolerate a dead socket). */
@@ -93,30 +87,22 @@ export class ApprovalBridge {
93
87
  if (signal?.aborted) return Promise.resolve<ApprovalOutcome>('cancelled')
94
88
  const approvalId = randomUUID()
95
89
  return new Promise<ApprovalOutcome>((resolve, reject) => {
96
- const entry: PendingApproval = {
90
+ this.waterfalls.register({
91
+ id: approvalId,
97
92
  sessionId: routingSessionId,
98
- settled: false,
99
93
  signal,
94
+ payload: undefined,
100
95
  complete: (outcome) => {
101
- if (entry.settled) return
102
- entry.settled = true
103
- this.pending.delete(approvalId)
104
- if (entry.onAbort !== undefined) entry.signal?.removeEventListener('abort', entry.onAbort)
105
96
  if (outcome.kind === 'decide') resolve(outcome.outcome)
106
97
  else next().then(resolve, reject)
107
98
  },
108
- onAbort: undefined,
109
- }
110
- if (signal !== undefined) {
111
- entry.onAbort = () => {
99
+ onAbort: () => {
112
100
  // Withdraw the card before settling so a late click can never be
113
101
  // reported as accepted for a dead request.
114
102
  this.deps.push({ t: 'approval.resolved', id: approvalId, sessionId: routingSessionId })
115
- entry.complete({ kind: 'decide', outcome: 'cancelled' })
116
- }
117
- signal.addEventListener('abort', entry.onAbort, { once: true })
118
- }
119
- this.pending.set(approvalId, entry)
103
+ this.waterfalls.settle(approvalId, { kind: 'decide', outcome: 'cancelled' })
104
+ },
105
+ })
120
106
  this.deps.push({
121
107
  t: 'approval.requested',
122
108
  id: approvalId,
@@ -133,28 +119,25 @@ export class ApprovalBridge {
133
119
  * rpc. The server replies with this receipt.
134
120
  */
135
121
  decide(args: ApprovalDecisionArgs): ApprovalReceipt {
136
- const entry = this.pending.get(args.approvalId)
137
- if (entry === undefined || entry.settled || entry.sessionId !== args.sessionId) {
122
+ if (!this.waterfalls.matches(args.approvalId, args.sessionId)) {
138
123
  return { accepted: false, reason: 'not-pending' }
139
124
  }
140
125
  if (args.decision !== 'allowed-once' && args.decision !== 'rejected') {
141
126
  return { accepted: false, reason: 'bad-decision' }
142
127
  }
143
- entry.complete({ kind: 'decide', outcome: args.decision })
128
+ this.waterfalls.settle(args.approvalId, { kind: 'decide', outcome: args.decision })
144
129
  return { accepted: true }
145
130
  }
146
131
 
147
132
  /** Bridge connection replaced/closed: delegate every unsettled approval. */
148
133
  delegateAll(): void {
149
- for (const entry of [...this.pending.values()]) {
150
- if (!entry.settled) entry.complete({ kind: 'delegate' })
151
- }
134
+ for (const id of this.waterfalls.ids()) this.waterfalls.settle(id, { kind: 'delegate' })
152
135
  }
153
136
 
154
137
  /** Plugin unload: answer everything fail-closed so no tool call outlives the plugin. */
155
138
  dispose(): void {
156
- for (const entry of [...this.pending.values()]) {
157
- if (!entry.settled) entry.complete({ kind: 'decide', outcome: 'unavailable' })
139
+ for (const id of this.waterfalls.ids()) {
140
+ this.waterfalls.settle(id, { kind: 'decide', outcome: 'unavailable' })
158
141
  }
159
142
  }
160
143
  }
@@ -85,7 +85,7 @@ export interface OwnershipSources {
85
85
  }
86
86
 
87
87
  /** Maximum ancestor hops when looking for an owned session. */
88
- export const MAX_OWNER_DEPTH = 8
88
+ const MAX_OWNER_DEPTH = 8
89
89
 
90
90
  /** Whether one exact session id is extension-owned by either source. */
91
91
  export function isOwnedSession(sessionId: string | undefined, sources: OwnershipSources): boolean {
@@ -151,21 +151,3 @@ export function resolveInteractionOwnership(input: {
151
151
  if (sessionId === undefined) return { owned: false, reason: 'not-owned' }
152
152
  return { owned: true, sessionId }
153
153
  }
154
-
155
- /**
156
- * Decide whether the bridge should own ask_user_question for this request.
157
- * Thin compatibility wrapper over {@link resolveInteractionOwnership}.
158
- */
159
- export function shouldBridgeOwnQuestion(input: {
160
- hasExtensionConnection: boolean
161
- clientSupportsQuestions: boolean
162
- sessionId: string | undefined
163
- extensionSessions: Pick<ExtensionSessionRegistry, 'has'>
164
- }): boolean {
165
- return resolveInteractionOwnership({
166
- hasExtensionConnection: input.hasExtensionConnection,
167
- clientSupports: input.clientSupportsQuestions,
168
- sessionId: input.sessionId,
169
- sources: { driven: input.extensionSessions },
170
- }).owned
171
- }
package/src/index.ts CHANGED
@@ -32,6 +32,7 @@ import type {} from '@deepseek-ai/dsh-tools'
32
32
  import type {} from '@deepseek-ai/dsh-api-gateway/types'
33
33
  import type {} from '@deepseek-ai/dsh-user-questions/types'
34
34
  import type { ApprovalRequestEvent } from '@deepseek-ai/dsh-user-approval/types'
35
+ import type { SessionId } from '@deepseek-ai/dsh-session/types'
35
36
  import type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
36
37
  import { readFileSync } from 'node:fs'
37
38
  import { dshHomePath } from '@deepseek-ai/dsh-home-paths'
@@ -192,10 +193,13 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
192
193
  const ownershipSources = { driven: extensionSessions, followed: followedSessions }
193
194
  // Subagent child sessions inherit their parent's ownership: a question asked
194
195
  // by a delegated agent belongs in the conversation the user is watching.
195
- const sessions = ctx.get('sessions')
196
- const parentOf = sessions === undefined
197
- ? undefined
198
- : (sessionId: string): string | undefined => sessions.get(sessionId as never)?.header.parentSession
196
+ // The Session store is read lazily on every hop: capturing it once at mount
197
+ // would silently disable inheritance whenever it is registered after this
198
+ // plugin (or recreated by an HMR reload).
199
+ const parentOf = (sessionId: string): string | undefined => {
200
+ const sessions = ctx.get('sessions')
201
+ return sessions?.get(sessionId as SessionId)?.header.parentSession
202
+ }
199
203
  const notingDispatchRpc: RpcDispatch = async (method, args, signal) => {
200
204
  const tracksOwnership = method === 'session/create' || method === 'session/prompt'
201
205
  const dispatched = tracksOwnership ? sessionIdOf(args.request) : undefined
@@ -277,8 +281,12 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
277
281
  // Prepended so the claim runs before the Remote event forwarding listener
278
282
  // in dsh-api-remotes. Delegations are logged with the failing gate so an
279
283
  // "invisible card" report is diagnosable from the host log.
284
+ // 委托日志:只有「扩展在线但不支持该卡片」是用户可操作的(扩展版本旧),
285
+ // 其余(无连接、会话不归属)在 dsh web 会话里每次都发生,压到 debug 免得刷屏。
280
286
  const logDelegation = (kind: 'user-questions' | 'approval', sessionId: string | undefined, reason: DelegateReason): void => {
281
- ctx.logger.info(`browser bridge: delegated ${kind} for session ${sessionId ?? '<unknown>'} (${reason})`)
287
+ const line = `browser bridge: delegated ${kind} for session ${sessionId ?? '<unknown>'} (${reason})`
288
+ if (reason === 'unsupported-client') ctx.logger.info(line)
289
+ else ctx.logger.debug(line)
282
290
  }
283
291
  ctx.effect(() => {
284
292
  const disposeListener = ctx.on('user-questions/request', (request, next) => {
@@ -287,7 +295,7 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
287
295
  clientSupports: server.clientSupportsQuestions(),
288
296
  sessionId: request.agent?.id,
289
297
  sources: ownershipSources,
290
- ...(parentOf === undefined ? {} : { parentOf }),
298
+ parentOf,
291
299
  })
292
300
  if (!ownership.owned) {
293
301
  logDelegation('user-questions', request.agent?.id, ownership.reason)
@@ -310,18 +318,19 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
310
318
  clientSupports: server.clientSupportsApprovals(),
311
319
  sessionId: request.agent?.id,
312
320
  sources: ownershipSources,
313
- ...(parentOf === undefined ? {} : { parentOf }),
321
+ parentOf,
314
322
  })
315
323
  if (!ownership.owned) {
316
324
  logDelegation('approval', request.agent?.id, ownership.reason)
317
325
  return next()
318
326
  }
327
+ const reason = approvalReasonText(request)
319
328
  return approvals.ask(
320
329
  ownership.sessionId,
321
330
  {
322
331
  toolName: request.toolName,
323
332
  ...(typeof request.callId === 'string' ? { callId: request.callId } : {}),
324
- ...(approvalReasonText(request) === undefined ? {} : { reason: approvalReasonText(request) as string }),
333
+ ...(reason === undefined ? {} : { reason }),
325
334
  },
326
335
  next,
327
336
  request.signal,
package/src/questions.ts CHANGED
@@ -18,6 +18,7 @@
18
18
 
19
19
  import { randomUUID } from 'node:crypto'
20
20
  import type { QuestionItem, ServerFrame } from './protocol.ts'
21
+ import { PendingWaterfalls } from './waterfall.ts'
21
22
 
22
23
  /** One answer item, mirroring the host AskUserQuestionAnswerItem wire form. */
23
24
  export interface QuestionAnswerItem {
@@ -49,15 +50,6 @@ type PendingOutcome =
49
50
  | { kind: 'reject'; error: Error }
50
51
  | { kind: 'delegate' }
51
52
 
52
- interface PendingQuestion {
53
- readonly sessionId: string
54
- readonly questionIds: ReadonlySet<string>
55
- settled: boolean
56
- readonly complete: (outcome: PendingOutcome) => void
57
- readonly signal: AbortSignal | undefined
58
- onAbort: (() => void) | undefined
59
- }
60
-
61
53
  /** Error matching the host's ASK_ABORTED semantics (the service remaps it). */
62
54
  function abortedError(): Error {
63
55
  return new Error('ask_user_question was aborted before the user answered')
@@ -99,7 +91,7 @@ export function asQuestionAnswerArgs(value: unknown): QuestionAnswerArgs | undef
99
91
 
100
92
  /** Owns the user-questions waterfall for extension-driven sessions. */
101
93
  export class QuestionBridge {
102
- private readonly pending = new Map<string, PendingQuestion>()
94
+ private readonly waterfalls = new PendingWaterfalls<PendingOutcome, ReadonlySet<string>>()
103
95
 
104
96
  constructor(private readonly deps: {
105
97
  /** Push one server frame to the connected extension (must tolerate a dead socket). */
@@ -124,33 +116,28 @@ export class QuestionBridge {
124
116
  ): Promise<QuestionAnswerPayload> {
125
117
  if (signal?.aborted) return Promise.reject(abortedError())
126
118
  const questionId = randomUUID()
119
+ const questionIds = new Set(questions.map(question => question.id))
127
120
  return new Promise<QuestionAnswerPayload>((resolve, reject) => {
128
- const entry: PendingQuestion = {
121
+ const settle = (outcome: PendingOutcome): void => {
122
+ this.waterfalls.settle(questionId, outcome)
123
+ }
124
+ this.waterfalls.register({
125
+ id: questionId,
129
126
  sessionId,
130
- questionIds: new Set(questions.map(question => question.id)),
131
- settled: false,
132
127
  signal,
128
+ payload: questionIds,
133
129
  complete: (outcome) => {
134
- if (entry.settled) return
135
- entry.settled = true
136
- this.pending.delete(questionId)
137
- if (entry.onAbort !== undefined) entry.signal?.removeEventListener('abort', entry.onAbort)
138
130
  if (outcome.kind === 'answer') resolve(outcome.answer)
139
131
  else if (outcome.kind === 'reject') reject(outcome.error)
140
132
  else next().then(resolve, reject)
141
133
  },
142
- onAbort: undefined,
143
- }
144
- if (signal !== undefined) {
145
- entry.onAbort = () => {
134
+ onAbort: () => {
146
135
  // Tell the extension to drop the card before settling so a late
147
136
  // answer can never report acceptance for a dead request.
148
137
  this.deps.push({ t: 'question.resolved', id: questionId, sessionId })
149
- entry.complete({ kind: 'reject', error: abortedError() })
150
- }
151
- signal.addEventListener('abort', entry.onAbort, { once: true })
152
- }
153
- this.pending.set(questionId, entry)
138
+ settle({ kind: 'reject', error: abortedError() })
139
+ },
140
+ })
154
141
  this.deps.push({ t: 'question.requested', id: questionId, sessionId, questions })
155
142
  })
156
143
  }
@@ -160,33 +147,28 @@ export class QuestionBridge {
160
147
  * rpc. The server replies with this receipt.
161
148
  */
162
149
  answer(args: QuestionAnswerArgs): QuestionAnswerReceipt {
163
- const entry = this.pending.get(args.questionId)
164
- if (entry === undefined || entry.settled || entry.sessionId !== args.sessionId) {
150
+ if (!this.waterfalls.matches(args.questionId, args.sessionId)) {
165
151
  return { accepted: false, reason: 'not-pending' }
166
152
  }
167
153
  if (args.decline === true) {
168
- entry.complete({ kind: 'reject', error: declinedError() })
154
+ this.waterfalls.settle(args.questionId, { kind: 'reject', error: declinedError() })
169
155
  return { accepted: true }
170
156
  }
171
- const answer = asAnswerPayload(args.answer, entry.questionIds)
157
+ const answer = asAnswerPayload(args.answer, this.waterfalls.payloadOf(args.questionId) ?? new Set())
172
158
  if (answer === undefined) return { accepted: false, reason: 'bad-answer' }
173
- entry.complete({ kind: 'answer', answer })
159
+ this.waterfalls.settle(args.questionId, { kind: 'answer', answer })
174
160
  return { accepted: true }
175
161
  }
176
162
 
177
163
  /** Bridge connection replaced/closed: delegate every unsettled question. */
178
164
  delegateAll(): void {
179
- for (const entry of [...this.pending.values()]) {
180
- if (!entry.settled) entry.complete({ kind: 'delegate' })
181
- }
165
+ for (const id of this.waterfalls.ids()) this.waterfalls.settle(id, { kind: 'delegate' })
182
166
  }
183
167
 
184
168
  /** Plugin unload: reject everything so no tool call outlives the plugin. */
185
169
  dispose(): void {
186
- for (const entry of [...this.pending.values()]) {
187
- if (!entry.settled) {
188
- entry.complete({ kind: 'reject', error: new Error('browser bridge plugin was unloaded') })
189
- }
170
+ for (const id of this.waterfalls.ids()) {
171
+ this.waterfalls.settle(id, { kind: 'reject', error: new Error('browser bridge plugin was unloaded') })
190
172
  }
191
173
  }
192
174
  }
package/src/server.ts CHANGED
@@ -23,6 +23,7 @@ import { randomUUID } from 'node:crypto'
23
23
  import type { IncomingMessage } from 'node:http'
24
24
  import type { Duplex } from 'node:stream'
25
25
  import { WebSocket, WebSocketServer } from 'ws'
26
+ import { followedSessionOf } from './session-follow.ts'
26
27
  import {
27
28
  HELLO_TIMEOUT_MS,
28
29
  PING_INTERVAL_MS,
@@ -93,10 +94,20 @@ function delay(ms: number): Promise<void> {
93
94
  /**
94
95
  * Race one promise against an abort signal. Resolves `undefined` when the
95
96
  * signal wins; the loser's handlers are always attached, so a late rejection
96
- * cannot surface as an unhandled rejection.
97
+ * cannot surface as an unhandled rejection — the host loader escalates those
98
+ * to a fatal load failure.
99
+ *
100
+ * Exported for tests.
97
101
  */
98
- function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T | undefined> {
99
- if (signal.aborted) return Promise.resolve(undefined)
102
+ export function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T | undefined> {
103
+ if (signal.aborted) {
104
+ // `promise` already exists: the caller evaluated it before entering this
105
+ // function, and an in-flight gateway stream rejects it with
106
+ // `gateway/cancelled` once the abort lands. Nobody else can observe it, so
107
+ // absorb the rejection instead of leaking an unhandled one.
108
+ promise.catch(() => undefined)
109
+ return Promise.resolve(undefined)
110
+ }
100
111
  return new Promise<T | undefined>((resolve, reject) => {
101
112
  const onAbort = (): void => { resolve(undefined) }
102
113
  signal.addEventListener('abort', onAbort, { once: true })
@@ -119,14 +130,6 @@ function orderedSessionId(frame: Extract<ClientFrame, { t: 'rpc' }>): string | u
119
130
  return typeof sessionId === 'string' ? sessionId : undefined
120
131
  }
121
132
 
122
- /** Session id carried by a `session/follow` stream's native args. */
123
- function followedSessionOf(args: Record<string, unknown>): string | undefined {
124
- const request = args.request
125
- if (typeof request !== 'object' || request === null || Array.isArray(request)) return undefined
126
- const sessionId = (request as Record<string, unknown>).sessionId
127
- return typeof sessionId === 'string' && sessionId.length > 0 ? sessionId : undefined
128
- }
129
-
130
133
  /** Loopback IPv4/IPv6 literals (IPv4-mapped included). Exported for tests and reuse. */
131
134
  export function isLoopbackAddress(address: string | undefined): boolean {
132
135
  return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
@@ -214,8 +217,6 @@ interface PendingTool {
214
217
  interface OpenStream {
215
218
  abort: AbortController
216
219
  pump: Promise<void>
217
- /** Session a `session/follow` stream is displaying, for interaction ownership. */
218
- followedSessionId?: string
219
220
  }
220
221
 
221
222
  /** A socket that passed authentication and owns the single active slot. */
@@ -614,6 +615,12 @@ export class BridgeServer {
614
615
  const iterable = await this.deps.openStream(frame.method, frame.args, abort.signal)
615
616
  iterator = iterable[Symbol.asyncIterator]()
616
617
  for (;;) {
618
+ // Never start another pull once the stream is cancelled: the gateway
619
+ // rejects an in-flight next() with `gateway/cancelled`, and a pull
620
+ // started after the abort would have no observer left to handle it
621
+ // (raceAbort stays as the safety net for the narrower race where the
622
+ // promise already exists).
623
+ if (abort.signal.aborted) break
617
624
  // Race every next() against abort: an idle follow stream can sit in
618
625
  // next() for hours, and abort-as-advice alone would leave the pump
619
626
  // (and close()) hanging until the gateway feels like answering.
@@ -625,7 +632,10 @@ export class BridgeServer {
625
632
  }
626
633
  } catch (error: unknown) {
627
634
  if (!abort.signal.aborted && ws.readyState === WebSocket.OPEN) {
628
- sendFrame(ws, { t: 'stream.error', id: frame.id, message: String(error) })
635
+ // Reporting must never throw: the socket can die between the
636
+ // readiness check and the write, and a throw here would escape the
637
+ // pump as an unhandled rejection.
638
+ try { sendFrame(ws, { t: 'stream.error', id: frame.id, message: String(error) }) } catch { /* socket died mid-report */ }
629
639
  }
630
640
  } finally {
631
641
  // Withdraw the subscription explicitly: for-await's implicit return()
@@ -638,15 +648,19 @@ export class BridgeServer {
638
648
  if (current !== null && current.streams.get(frame.id)?.pump === pump) {
639
649
  current.streams.delete(frame.id)
640
650
  }
641
- if (followedSessionId !== undefined) this.deps.onFollowChanged?.(followedSessionId, false)
651
+ if (followedSessionId !== undefined) {
652
+ try { this.deps.onFollowChanged?.(followedSessionId, false) } catch { /* ownership bookkeeping is best-effort */ }
653
+ }
642
654
  }
643
655
  })()
644
- conn.streams.set(frame.id, {
645
- abort,
646
- pump,
647
- ...(followedSessionId === undefined ? {} : { followedSessionId }),
648
- })
649
- if (followedSessionId !== undefined) this.deps.onFollowChanged?.(followedSessionId, true)
656
+ conn.streams.set(frame.id, { abort, pump })
657
+ // Last-resort guard: the pump reports its own failures through
658
+ // `stream.error`, but a rejection escaping it would reach the host loader
659
+ // as an unhandled rejection and abort the whole plugin load.
660
+ void pump.catch(() => { /* already reported above */ })
661
+ if (followedSessionId !== undefined) {
662
+ try { this.deps.onFollowChanged?.(followedSessionId, true) } catch { /* ownership bookkeeping is best-effort */ }
663
+ }
650
664
  }
651
665
 
652
666
  /**
@@ -0,0 +1,76 @@
1
+ /**
2
+ * `session/follow` 的参数形状:宿主描述符要求
3
+ * `{request: {address: SessionAddress}}`,其中 address 是
4
+ * `{kind:'session', sessionId}` 或
5
+ * `{kind:'subagent', parentSessionId, childSessionId, mode}`。
6
+ *
7
+ * 扩展用 {@link sessionFollowArgs} 构造订阅参数,插件用
8
+ * {@link followedSessionOf} 从原生 args 里取回「正在展示哪个会话」。两者
9
+ * 同处一个模块,是为了让形状只有**一个**真实来源:0.4.7 曾因插件侧测试用
10
+ * 臆造形状(`request.sessionId`)而没发现 follow 归属在生产环境从未生效。
11
+ *
12
+ * @module @deepseek-ai/dsh-bridge-browser/src/session-follow
13
+ */
14
+
15
+ /** 普通会话的 follow 地址。 */
16
+ export interface SessionFollowAddress {
17
+ kind: 'session'
18
+ sessionId: string
19
+ }
20
+
21
+ /** 直接 subagent 子会话的 follow 地址(宿主 SessionAddress 的另一形态)。 */
22
+ export interface SubagentFollowAddress {
23
+ kind: 'subagent'
24
+ parentSessionId: string
25
+ childSessionId: string
26
+ mode: 'one-shot' | 'continuable' | 'unknown'
27
+ }
28
+
29
+ /** 一次性订阅参数(`stream.open` 的 args)。 */
30
+ export interface SessionFollowArgs {
31
+ request: {
32
+ address: SessionFollowAddress | SubagentFollowAddress
33
+ }
34
+ }
35
+
36
+ /** 订阅一个普通会话(面板当前会话始终用这一形态)。 */
37
+ export function sessionFollowArgs(sessionId: string): SessionFollowArgs {
38
+ return { request: { address: { kind: 'session', sessionId } } }
39
+ }
40
+
41
+ /** 订阅一个 direct subagent 子会话(预留:目前面板不展示子会话)。 */
42
+ export function subagentFollowArgs(
43
+ parentSessionId: string,
44
+ childSessionId: string,
45
+ mode: SubagentFollowAddress['mode'] = 'unknown',
46
+ ): SessionFollowArgs {
47
+ return { request: { address: { kind: 'subagent', parentSessionId, childSessionId, mode } } }
48
+ }
49
+
50
+ /**
51
+ * Session id displayed by a `session/follow` stream, read from the host's
52
+ * `SessionFollowRequest.address`. A subagent address carries the child session
53
+ * on `childSessionId`; ownership then walks up to the parent conversation, so
54
+ * either form routes the card correctly.
55
+ *
56
+ * @param args - native args of the `stream.open` frame.
57
+ * @returns the followed session id, or undefined when absent/malformed.
58
+ */
59
+ export function followedSessionOf(args: Record<string, unknown>): string | undefined {
60
+ const request = args.request
61
+ if (typeof request !== 'object' || request === null || Array.isArray(request)) return undefined
62
+ const address = (request as Record<string, unknown>).address
63
+ if (typeof address !== 'object' || address === null || Array.isArray(address)) return undefined
64
+ const fields = address as Record<string, unknown>
65
+ if (fields.kind === 'session') {
66
+ return nonEmptyString(fields.sessionId)
67
+ }
68
+ if (fields.kind === 'subagent') {
69
+ return nonEmptyString(fields.childSessionId)
70
+ }
71
+ return undefined
72
+ }
73
+
74
+ function nonEmptyString(value: unknown): string | undefined {
75
+ return typeof value === 'string' && value.length > 0 ? value : undefined
76
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Bookkeeping shared by the host waterfalls the bridge claims
3
+ * (`user-questions/request`, `approval/request`).
4
+ *
5
+ * Both bridges need exactly the same lifecycle: one pending entry per
6
+ * generated id, a **single settlement** guarantee against concurrent paths
7
+ * (extension answer vs host abort vs connection loss vs plugin unload), an
8
+ * abort listener that is detached once settled, and the id+session match the
9
+ * uplink must pass before it may touch an entry. Only the outcome vocabulary
10
+ * and the push/settle policy differ, and those stay in the domain modules.
11
+ *
12
+ * @module
13
+ */
14
+
15
+ interface Entry<TOutcome, TPayload> {
16
+ readonly sessionId: string
17
+ /** Domain state the uplink needs (e.g. the question ids one card asked about). */
18
+ readonly payload: TPayload
19
+ /** Domain policy for one settlement; invoked at most once per id. */
20
+ readonly complete: (outcome: TOutcome) => void
21
+ readonly signal: AbortSignal | undefined
22
+ readonly onAbort: (() => void) | undefined
23
+ settled: boolean
24
+ }
25
+
26
+ /** Registry of pending waterfall requests, keyed by the id sent to the extension. */
27
+ export class PendingWaterfalls<TOutcome, TPayload = undefined> {
28
+ private readonly entries = new Map<string, Entry<TOutcome, TPayload>>()
29
+
30
+ /**
31
+ * Track one request pushed to the extension.
32
+ *
33
+ * @param input - id, asking session, host cancellation signal, the domain's
34
+ * settlement policy, and the abort handler (typically: tell the extension
35
+ * the card is gone, then settle).
36
+ */
37
+ register(input: {
38
+ id: string
39
+ sessionId: string
40
+ signal: AbortSignal | undefined
41
+ payload: TPayload
42
+ complete: (outcome: TOutcome) => void
43
+ onAbort: () => void
44
+ }): void {
45
+ const entry: Entry<TOutcome, TPayload> = {
46
+ sessionId: input.sessionId,
47
+ payload: input.payload,
48
+ complete: input.complete,
49
+ signal: input.signal,
50
+ onAbort: input.onAbort,
51
+ settled: false,
52
+ }
53
+ if (input.signal !== undefined) input.signal.addEventListener('abort', input.onAbort, { once: true })
54
+ this.entries.set(input.id, entry)
55
+ }
56
+
57
+ /**
58
+ * Whether an unsettled entry exists for exactly this id and session. The
59
+ * uplink must not be able to settle another session's card.
60
+ */
61
+ matches(id: string, sessionId: string): boolean {
62
+ const entry = this.entries.get(id)
63
+ return entry !== undefined && !entry.settled && entry.sessionId === sessionId
64
+ }
65
+
66
+ /** Domain payload registered with one unsettled entry (undefined once settled). */
67
+ payloadOf(id: string): TPayload | undefined {
68
+ return this.entries.get(id)?.payload
69
+ }
70
+
71
+ /**
72
+ * Settle one request. Later settlements for the same id are no-ops, and the
73
+ * entry is dropped together with its abort listener.
74
+ *
75
+ * @returns true when this call performed the settlement.
76
+ */
77
+ settle(id: string, outcome: TOutcome): boolean {
78
+ const entry = this.entries.get(id)
79
+ if (entry === undefined || entry.settled) return false
80
+ entry.settled = true
81
+ this.entries.delete(id)
82
+ if (entry.onAbort !== undefined) entry.signal?.removeEventListener('abort', entry.onAbort)
83
+ entry.complete(outcome)
84
+ return true
85
+ }
86
+
87
+ /** Every unsettled id, for the connection-loss and unload sweeps. */
88
+ ids(): string[] {
89
+ return [...this.entries.keys()]
90
+ }
91
+ }