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/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
  /**
File without changes
@@ -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
+ }
File without changes
package/src/token.ts CHANGED
File without changes
package/src/tools.ts CHANGED
File without changes
@@ -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
+ }
package/lib/invariant.js DELETED
@@ -1,26 +0,0 @@
1
- //#region lib/types/invariant.js
2
- /**
3
- * Package-owned invariant companion for `@deepseek-ai/dsh-bridge-browser`.
4
- * @module @deepseek-ai/dsh-bridge-browser/invariant
5
- */
6
- const PACKAGE_NAME = "@deepseek-ai/dsh-bridge-browser";
7
- /** Cordis companion plugin name. */
8
- const name = "bridge-browser-invariant";
9
- /** Service required before the companion can reserve package ownership. */
10
- const inject = ["invariants"];
11
- /**
12
- * No runtime invariant: the bridge's connection registry and pending tool map
13
- * are instance-private (no published event stream to assert against), and the
14
- * wire contract is pinned by protocol.ts and covered by its unit tests. The
15
- * tools are plain ctx.tools registrations observed by dsh-tools' own
16
- * invariant.
17
- */
18
- const install = () => {};
19
- /**
20
- * Register this package's invariant companion.
21
- * @param ctx - Cordis context carrying the invariant service.
22
- * @returns the installed registration's disposer after setup succeeds.
23
- */
24
- const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
25
- //#endregion
26
- export { apply, inject, name };
@@ -1,59 +0,0 @@
1
- /**
2
- * Session event pump: the alpha replacement for the rc `events.mux` SSE
3
- * aggregate. alpha exposes per-session `session/follow` Remote streams, so
4
- * this module maintains one follow stream per session the extension has
5
- * touched and fans their event frames out to every connected bridge client,
6
- * translated back to the rc `session/event` mux shape the extension renders.
7
- *
8
- * Snapshot frames are never replayed: the panel reconciles through
9
- * `session.history` at turn boundaries, so replaying the opening window would
10
- * duplicate rows it already drew.
11
- *
12
- * @module
13
- */
14
- import type { TypertGateway } from '@deepseek-ai/dsh-api-gateway/types';
15
- import type { SessionWireEvent } from '@deepseek-ai/dsh-api-session-controller/types';
16
- /** One translated event envelope, the bridge's local replacement for rc MuxFrame pushes. */
17
- export interface SessionEventEnvelope {
18
- readonly rpcId: string;
19
- readonly payload: {
20
- readonly type: 'session/event';
21
- readonly sessionId: string;
22
- readonly event: SessionWireEvent;
23
- };
24
- }
25
- /**
26
- * Multiplex `session/follow` streams onto bridge event subscribers. Shared by
27
- * all connections of one plugin instance; dispose with {@link close}.
28
- */
29
- export declare class SessionEventMux {
30
- private readonly gateway;
31
- private readonly warn;
32
- private readonly listeners;
33
- private readonly streams;
34
- private readonly warned;
35
- private closed;
36
- constructor(gateway: TypertGateway, warn: (message: string) => void);
37
- /**
38
- * Record that the extension addressed this session. The first touch opens
39
- * the session's follow stream; later touches are no-ops.
40
- */
41
- touch(sessionId: string): void;
42
- /** Stop every follow stream and drop all subscribers. */
43
- close(): void;
44
- /**
45
- * Subscribe one bridge connection: yields translated `session/event`
46
- * envelopes until the signal aborts. Late subscribers hear only future
47
- * events — history reconciliation owns the backlog.
48
- */
49
- openEvents(signal: AbortSignal): AsyncIterable<SessionEventEnvelope>;
50
- /**
51
- * One session's follow loop. Event frames are translated and broadcast;
52
- * failures reopen the stream after {@link FOLLOW_RETRY_MS} until the mux is
53
- * closed (a stream can outlive its session's visibility, and transient
54
- * resume failures must not silence a live session).
55
- */
56
- private follow;
57
- private broadcast;
58
- }
59
- //# sourceMappingURL=events.d.ts.map
@@ -1,87 +0,0 @@
1
- /**
2
- * rc→alpha gateway translation for the bridge RPC path.
3
- *
4
- * The browser extension speaks the rc-line bridge protocol: dot-joined method
5
- * names (`session.create`) and rc-shaped response envelopes. The alpha line
6
- * removed `ctx.apiProxy`; its `/api` carrier expects slash-joined endpoints
7
- * (`session/create`) and a strict `{ args: { request | _request } }` payload
8
- * envelope. This module is the ONLY place that knows both dialects: unary
9
- * methods are re-enveloped onto Connection's shared fetch handler, while
10
- * `workspace.list` and `session.history` (deleted in alpha) are synthesized
11
- * from the `workspace/follow` and `session/follow` Remote streams.
12
- *
13
- * @module
14
- */
15
- import type { ConnectionFetchHandler } from '@deepseek-ai/dsh-client-connection';
16
- import type { TypertGateway } from '@deepseek-ai/dsh-api-gateway/types';
17
- /** Success/failure result inside one server-response body. */
18
- export type GatewayResult = {
19
- readonly ok: true;
20
- readonly value: unknown;
21
- } | {
22
- readonly ok: false;
23
- readonly error: {
24
- readonly code: string;
25
- readonly message: string;
26
- readonly details?: object;
27
- };
28
- };
29
- /** The response body relayed verbatim as the extension's `rpc.result.result`. */
30
- export interface GatewayResponse {
31
- readonly type: 'server-response';
32
- readonly rpcId: string;
33
- readonly result: GatewayResult;
34
- }
35
- /**
36
- * One dispatch of a bridge RPC frame: dot-joined method plus the extension's
37
- * raw payload, answered with the rc-shaped server-response body. Business
38
- * failures ride the envelope (`result.ok: false`); only carrier-level
39
- * failures reject (see {@link GatewayDispatchError}).
40
- */
41
- export type RpcDispatch = (rpcId: string, method: string, payload: unknown) => Promise<GatewayResponse>;
42
- /** Carrier-level dispatch failure; `code` becomes the `rpc.result` error code. */
43
- export declare class GatewayDispatchError extends Error {
44
- readonly code: 'http' | 'internal';
45
- constructor(code: 'http' | 'internal', message: string);
46
- }
47
- /** Wrap one business value in the rc-shaped server-response body. */
48
- export declare function okResponse(rpcId: string, value: unknown): GatewayResponse;
49
- /** Wrap one business failure in the rc-shaped server-response body. */
50
- export declare function failResponse(rpcId: string, code: string, message: string, details?: object): GatewayResponse;
51
- /** Callback the gateway uses to report sessions the extension has addressed. */
52
- export type TouchSession = (sessionId: string) => void;
53
- export interface BridgeGatewayDeps {
54
- /** Authenticated `/api` carrier from `ctx.connection.createSharedFetchHandler('/api')`. */
55
- readonly fetchHandler: ConnectionFetchHandler;
56
- /** Live Typert Remote dispatcher (stream methods only; unary goes through the carrier). */
57
- readonly gateway: TypertGateway;
58
- /** Notified with every session id the extension addresses (drives the event pump). */
59
- readonly touch: TouchSession;
60
- /** Logger for degraded synthesized methods. */
61
- readonly warn: (message: string) => void;
62
- }
63
- /**
64
- * The bridge's alpha gateway face: unary translation onto the shared `/api`
65
- * carrier plus the two synthesized rc methods. Construct once per plugin
66
- * instance; wrap with the session-workspace/session-deferral interceptors,
67
- * then hand the outermost {@link RpcDispatch} to the bridge server.
68
- */
69
- export declare class BridgeGateway {
70
- private readonly deps;
71
- private readonly workspaces;
72
- constructor(deps: BridgeGatewayDeps);
73
- /** Bound dispatch, safe to wrap and hand to the bridge server. */
74
- readonly dispatch: RpcDispatch;
75
- /** Start the workspace/follow stream backing `workspace.list`. */
76
- start(): void;
77
- /** Stop owned streams (plugin dispose). */
78
- close(): void;
79
- private dispatchImpl;
80
- /**
81
- * alpha has no `session/history`: one short-lived `session/follow` stream
82
- * supplies its opening snapshot, whose records replay exactly what the rc
83
- * tail page carried (`{ event }` entries plus `hasMore`).
84
- */
85
- private sessionHistory;
86
- }
87
- //# sourceMappingURL=gateway.d.ts.map
@@ -1,16 +0,0 @@
1
- /**
2
- * Package-owned invariant companion for `@deepseek-ai/dsh-bridge-browser`.
3
- * @module @deepseek-ai/dsh-bridge-browser/invariant
4
- */
5
- import type { Context } from '@deepseek-ai/cordis';
6
- /** Cordis companion plugin name. */
7
- export declare const name = "bridge-browser-invariant";
8
- /** Service required before the companion can reserve package ownership. */
9
- export declare const inject: string[];
10
- /**
11
- * Register this package's invariant companion.
12
- * @param ctx - Cordis context carrying the invariant service.
13
- * @returns the installed registration's disposer after setup succeeds.
14
- */
15
- export declare const apply: (ctx: Context) => Promise<() => void>;
16
- //# sourceMappingURL=invariant.d.ts.map
package/src/invariant.ts DELETED
@@ -1,33 +0,0 @@
1
- /**
2
- * Package-owned invariant companion for `@deepseek-ai/dsh-bridge-browser`.
3
- * @module @deepseek-ai/dsh-bridge-browser/invariant
4
- */
5
-
6
- /* jscpd:ignore-start */
7
- import type { Context } from '@deepseek-ai/cordis'
8
- import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
9
-
10
- const PACKAGE_NAME = '@deepseek-ai/dsh-bridge-browser'
11
-
12
- /** Cordis companion plugin name. */
13
- export const name = 'bridge-browser-invariant'
14
- /** Service required before the companion can reserve package ownership. */
15
- export const inject = ['invariants']
16
-
17
- /**
18
- * No runtime invariant: the bridge's connection registry and pending tool map
19
- * are instance-private (no published event stream to assert against), and the
20
- * wire contract is pinned by protocol.ts and covered by its unit tests. The
21
- * tools are plain ctx.tools registrations observed by dsh-tools' own
22
- * invariant.
23
- */
24
- const install: InvariantInstaller = () => {}
25
-
26
- /**
27
- * Register this package's invariant companion.
28
- * @param ctx - Cordis context carrying the invariant service.
29
- * @returns the installed registration's disposer after setup succeeds.
30
- */
31
- export const apply = (ctx: Context): Promise<() => void> =>
32
- Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
33
- /* jscpd:ignore-end */