dsh-browser-firefox 0.3.2 → 0.4.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/index.ts CHANGED
@@ -4,11 +4,13 @@
4
4
  *
5
5
  * The bridge mounts its own upgrade route (`/ext/bridge`) on the host
6
6
  * webserver, OUTSIDE the /api trust fence — so it brings its own bearer-token
7
- * authentication (first frame `hello` within HELLO_TIMEOUT_MS). Gateway RPCs
8
- * from the extension are dispatched through the same fetch-shaped handler the
9
- * /api carrier uses, and session events are pumped per connection. Tools
10
- * execute by dispatching `tool.call` frames to the connected extension, which
11
- * performs the action in the user's active tab.
7
+ * authentication (first frame `hello` within HELLO_TIMEOUT_MS). The wire
8
+ * protocol IS the alpha Typert Remote dialect: unary `rpc` frames carry
9
+ * slash-joined endpoints and native args objects straight into
10
+ * `ctx.typertGateway.invoke`, and `stream.open` frames open
11
+ * `ctx.typertGateway.stream` subscriptions whose native follow frames flow
12
+ * back unmodified. Tools execute by dispatching `tool.call` frames to the
13
+ * connected extension, which performs the action in the user's active tab.
12
14
  *
13
15
  * Opt-in by design: nothing is registered unless this plugin appears in the
14
16
  * composition. No dsh core code is touched.
@@ -16,28 +18,24 @@
16
18
  * @module @deepseek-ai/dsh-bridge-browser
17
19
  */
18
20
 
19
- import { randomUUID } from 'node:crypto'
20
21
  import type { Context } from '@deepseek-ai/cordis'
21
22
  import z from '@deepseek-ai/schemastery'
22
23
  import type {} from '@deepseek-ai/dsh-tools'
23
- import type {} from '@deepseek-ai/dsh-host-apiproxy'
24
+ import type {} from '@deepseek-ai/dsh-api-gateway/types'
24
25
  import type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
25
- import type { ApiProxy } from '@deepseek-ai/dsh-host-apiproxy/api'
26
- import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api'
27
- import { toFetchHandler } from '@deepseek-ai/dsh-host-apiproxy'
28
26
  import { dshHomePath } from '@deepseek-ai/dsh-home-paths'
29
27
  import { BridgeServer } from './server.ts'
30
28
  import { registerBrowserTools } from './tools.ts'
31
- import { BRIDGE_CONFIG_PATH, BRIDGE_PATH } from './protocol.ts'
29
+ import { BRIDGE_CONFIG_PATH, BRIDGE_PATH, type RemoteWireResult } from './protocol.ts'
32
30
  import { withSessionDeferral } from './session-deferral.ts'
33
- import { withSessionWorkspace } from './session-workspace.ts'
31
+ import { withSessionWorkspace, type RpcDispatch } from './session-workspace.ts'
34
32
  import { resolveToken } from './token.ts'
35
33
 
36
34
  /** Cordis plugin name used by loader diagnostics. */
37
35
  export const name = 'bridge-browser'
38
36
 
39
37
  /** Services required by this plugin. */
40
- export const inject = ['webServer', 'apiProxy', 'tools']
38
+ export const inject = ['webServer', 'typertGateway', 'tools']
41
39
 
42
40
  /** Default per-tool-call budget (ms). */
43
41
  const DEFAULT_TOOL_TIMEOUT_MS = 60_000
@@ -120,11 +118,27 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
120
118
  const resolved = resolveConfig(config)
121
119
 
122
120
  const tokenRes = await resolveToken(resolved.token)
123
- // Workspace grouping wraps the gateway create; session deferral wraps the
121
+ // Base dispatch: split the slash-joined endpoint and invoke the Remote
122
+ // method; Remote failures are folded into the wire result (never thrown
123
+ // across the bridge), everything else is an internal failure.
124
+ const invoke: RpcDispatch = async (method, args, signal) => {
125
+ const slash = method.indexOf('/')
126
+ const namespace = slash === -1 ? method : method.slice(0, slash)
127
+ const remoteMethod = slash === -1 ? '' : method.slice(slash + 1)
128
+ try {
129
+ const value = await ctx.typertGateway.invoke({ namespace, method: remoteMethod, args, signal })
130
+ return { ok: true, value }
131
+ } catch (error: unknown) {
132
+ const failure = ctx.typertGateway.wireStream.failure(error)
133
+ const result: RemoteWireResult = { ok: false, error: failure }
134
+ return result
135
+ }
136
+ }
137
+ // Workspace grouping intercepts session/create; session deferral wraps the
124
138
  // result so materialization at first prompt still flows through grouping.
125
- const api: ApiProxy = withSessionDeferral(
139
+ const dispatchRpc = withSessionDeferral(
126
140
  withSessionWorkspace(
127
- ctx.apiProxy,
141
+ invoke,
128
142
  resolved.sessionWorkspacePath,
129
143
  message => { ctx.logger.warn(message) },
130
144
  ),
@@ -132,8 +146,13 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
132
146
  )
133
147
  const server = new BridgeServer({
134
148
  token: tokenRes.token,
135
- apiHandler: toFetchHandler(api),
136
- openEvents: (signal) => api.events.mux({ rpcId: RpcId(randomUUID()), payload: {} }, signal),
149
+ dispatchRpc,
150
+ openStream: (method, args, signal) => {
151
+ const slash = method.indexOf('/')
152
+ const namespace = slash === -1 ? method : method.slice(0, slash)
153
+ const remoteMethod = slash === -1 ? '' : method.slice(slash + 1)
154
+ return ctx.typertGateway.stream({ namespace, method: remoteMethod, args, signal })
155
+ },
137
156
  toolTimeoutMs: resolved.toolTimeoutMs,
138
157
  caps: {
139
158
  textOnly: true,
@@ -157,8 +176,18 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
157
176
  const configRoute: WebRoute = {
158
177
  kind: 'exact',
159
178
  path: BRIDGE_CONFIG_PATH,
160
- handler: (_req, res) => {
161
- res.writeHead(200, { 'content-type': 'application/json' })
179
+ handler: (req, res) => {
180
+ // CORS: browser extensions fetch this from their own origin during
181
+ // bridge auto-detection. Firefox enforces CORS on extension fetches
182
+ // (Chrome with host_permissions does not) — without ACAO the discovery
183
+ // response is unreadable and the extension never learns the WS URL.
184
+ const cors = { 'access-control-allow-origin': '*' }
185
+ if (req.method === 'OPTIONS') {
186
+ res.writeHead(204, { ...cors, 'access-control-allow-methods': 'GET, OPTIONS' })
187
+ res.end()
188
+ return
189
+ }
190
+ res.writeHead(200, { 'content-type': 'application/json', ...cors })
162
191
  res.end(JSON.stringify({ wsUrl: `ws://127.0.0.1:${ctx.webServer.port}${BRIDGE_PATH}` }))
163
192
  },
164
193
  }
package/src/protocol.ts CHANGED
@@ -2,13 +2,19 @@
2
2
  * Wire contract between the dsh bridge plugin and the browser extension.
3
3
  *
4
4
  * Zero-dependency module (pure types, constants, and a parser): both the
5
- * plugin (node) and the Chrome extension (browser bundle) import this file, so
6
- * the frame shapes can never drift between the two halves.
5
+ * plugin (node) and the Firefox extension (browser bundle) import this file,
6
+ * so the frame shapes can never drift between the two halves.
7
7
  *
8
8
  * Frames are one JSON object per WebSocket message, discriminated by `t`.
9
9
  * Correlation ids (`id`) are minted by the requestor and echoed by the
10
10
  * responder; they are opaque strings, never parsed.
11
11
  *
12
+ * The RPC/stream vocabulary is the alpha Typert Remote dialect verbatim:
13
+ * methods are slash-joined endpoints (`session/create`), `args` is the Remote
14
+ * descriptor's native args object (`{ request: {...} }`, `{ _request: {} }`),
15
+ * and stream frames carry the native Session/Workspace follow frames
16
+ * unmodified.
17
+ *
12
18
  * @module
13
19
  */
14
20
 
@@ -53,12 +59,28 @@ export interface BridgeCaps {
53
59
  maxInteractiveItems: number
54
60
  }
55
61
 
62
+ /** One Remote failure as plain wire data (RemoteError's message is non-enumerable, so it is restated explicitly). */
63
+ export interface RemoteWireFailure {
64
+ code: string
65
+ message: string
66
+ details?: object
67
+ }
68
+
69
+ /** The RemoteResult wire form answered to one `rpc` frame. */
70
+ export type RemoteWireResult =
71
+ | { ok: true; value: unknown }
72
+ | { ok: false; error: RemoteWireFailure }
73
+
56
74
  /** Frames sent by the extension to the bridge plugin. */
57
75
  export type ClientFrame =
58
76
  /** First frame, within HELLO_TIMEOUT_MS of socket open. */
59
77
  | { t: 'hello'; token: string; caps: BridgeCaps }
60
- /** Unary gateway RPC passthrough (method names from the apiproxy RpcMethodMap). */
61
- | { t: 'rpc'; id: string; method: string; payload: unknown }
78
+ /** Unary Remote call: slash-joined endpoint plus the descriptor's native args object. */
79
+ | { t: 'rpc'; id: string; method: string; args: Record<string, unknown> }
80
+ /** Open one Remote stream (`session/follow`, `workspace/follow`); frames arrive as `stream.frame`. */
81
+ | { t: 'stream.open'; id: string; method: string; args: Record<string, unknown> }
82
+ /** Cancel one open stream. */
83
+ | { t: 'stream.close'; id: string }
62
84
  /** Result of a previously dispatched tool call. */
63
85
  | { t: 'tool.result'; id: string; ok: true; result: unknown }
64
86
  | { t: 'tool.result'; id: string; ok: false; error: ToolError }
@@ -69,11 +91,13 @@ export type ClientFrame =
69
91
  export type ServerFrame =
70
92
  /** Accepted after a valid `hello`. */
71
93
  | { t: 'hello.ok'; caps: BridgeCaps }
72
- /** Reply to an `rpc` frame; `result` is the apiproxy ServerResponse envelope. */
73
- | { t: 'rpc.result'; id: string; ok: true; result: unknown }
74
- | { t: 'rpc.result'; id: string; ok: false; error: { code: string; message: string } }
75
- /** One gateway event envelope (the same server-request shape the GUI's /api/events.mux carries). */
76
- | { t: 'event'; frame: { rpcId: string; method: string; payload: unknown } }
94
+ /** Reply to an `rpc` frame: the RemoteResult wire form, flattened onto the frame. */
95
+ | { t: 'rpc.result'; id: string; ok: true; value: unknown }
96
+ | { t: 'rpc.result'; id: string; ok: false; error: RemoteWireFailure }
97
+ /** One native frame of an open stream (SessionFollowFrame / WorkspaceFollowFrame, unmodified). */
98
+ | { t: 'stream.frame'; id: string; frame: unknown }
99
+ /** A stream failed (or its open was rejected); the client may reopen it. */
100
+ | { t: 'stream.error'; id: string; message: string }
77
101
  /** A model-requested browser action to execute in the user-controlled tab. `expiresAt` (ms epoch) withdraws the call once the caller stops waiting. */
78
102
  | { t: 'tool.call'; id: string; name: string; args: Record<string, unknown>; expiresAt?: number; sessionId?: string; title?: string }
79
103
  /** Withdraw a tool call that timed out or whose caller was cancelled. */
@@ -88,15 +112,16 @@ export type BridgeFrame = ClientFrame | ServerFrame
88
112
 
89
113
  /**
90
114
  * Type guard: is this frame one the SERVER may send? Client-only shapes
91
- * (hello/tool.result/pong) narrow out, so server-side consumers never
92
- * dispatch on their own request vocabulary.
115
+ * (hello/rpc/stream.open/stream.close/tool.result/pong) narrow out, so
116
+ * server-side consumers never dispatch on their own request vocabulary.
93
117
  * @param frame - parsed frame.
94
118
  * @returns true for server-sendable frames.
95
119
  */
96
120
  export function isServerFrame(frame: BridgeFrame): frame is ServerFrame {
97
121
  return frame.t === 'hello.ok'
98
122
  || frame.t === 'rpc.result'
99
- || frame.t === 'event'
123
+ || frame.t === 'stream.frame'
124
+ || frame.t === 'stream.error'
100
125
  || frame.t === 'tool.call'
101
126
  || frame.t === 'tool.cancel'
102
127
  || frame.t === 'ping'
@@ -110,7 +135,17 @@ export function isServerFrame(frame: BridgeFrame): frame is ServerFrame {
110
135
  * @returns true for client-sendable frames.
111
136
  */
112
137
  export function isClientFrame(frame: BridgeFrame): frame is ClientFrame {
113
- return frame.t === 'hello' || frame.t === 'rpc' || frame.t === 'tool.result' || frame.t === 'pong'
138
+ return frame.t === 'hello'
139
+ || frame.t === 'rpc'
140
+ || frame.t === 'stream.open'
141
+ || frame.t === 'stream.close'
142
+ || frame.t === 'tool.result'
143
+ || frame.t === 'pong'
144
+ }
145
+
146
+ /** Wire args must be a plain object (the Remote descriptor's named arguments). */
147
+ function isArgs(value: unknown): value is Record<string, unknown> {
148
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
114
149
  }
115
150
 
116
151
  /**
@@ -135,9 +170,15 @@ export function parseBridgeFrame(text: string): BridgeFrame | undefined {
135
170
  ? { t: 'hello', token: frame.token, caps: frame.caps }
136
171
  : undefined
137
172
  case 'rpc':
138
- return typeof frame.id === 'string' && typeof frame.method === 'string'
139
- ? { t: 'rpc', id: frame.id, method: frame.method, payload: frame.payload }
173
+ return typeof frame.id === 'string' && typeof frame.method === 'string' && isArgs(frame.args)
174
+ ? { t: 'rpc', id: frame.id, method: frame.method, args: frame.args }
175
+ : undefined
176
+ case 'stream.open':
177
+ return typeof frame.id === 'string' && typeof frame.method === 'string' && isArgs(frame.args)
178
+ ? { t: 'stream.open', id: frame.id, method: frame.method, args: frame.args }
140
179
  : undefined
180
+ case 'stream.close':
181
+ return typeof frame.id === 'string' ? { t: 'stream.close', id: frame.id } : undefined
141
182
  case 'tool.result':
142
183
  if (typeof frame.id !== 'string') return undefined
143
184
  if (frame.ok === true && 'result' in frame) {
@@ -154,15 +195,19 @@ export function parseBridgeFrame(text: string): BridgeFrame | undefined {
154
195
  : undefined
155
196
  case 'rpc.result':
156
197
  if (typeof frame.id !== 'string') return undefined
157
- if (frame.ok === true && 'result' in frame) {
158
- return { t: 'rpc.result', id: frame.id, ok: true, result: frame.result }
198
+ if (frame.ok === true && 'value' in frame) {
199
+ return { t: 'rpc.result', id: frame.id, ok: true, value: frame.value }
159
200
  }
160
- return typeof frame.error === 'object' && frame.error !== null
161
- ? { t: 'rpc.result', id: frame.id, ok: false, error: frame.error as { code: string; message: string } }
201
+ return isWireFailure(frame.error)
202
+ ? { t: 'rpc.result', id: frame.id, ok: false, error: frame.error }
203
+ : undefined
204
+ case 'stream.frame':
205
+ return typeof frame.id === 'string'
206
+ ? { t: 'stream.frame', id: frame.id, frame: frame.frame }
162
207
  : undefined
163
- case 'event':
164
- return typeof frame.frame === 'object' && frame.frame !== null
165
- ? { t: 'event', frame: frame.frame as ServerFrame extends { t: 'event' } ? ServerFrame['frame'] : never }
208
+ case 'stream.error':
209
+ return typeof frame.id === 'string' && typeof frame.message === 'string'
210
+ ? { t: 'stream.error', id: frame.id, message: frame.message }
166
211
  : undefined
167
212
  case 'tool.call':
168
213
  if (typeof frame.id !== 'string' || typeof frame.name !== 'string') return undefined
@@ -206,3 +251,9 @@ function isToolError(value: unknown): value is ToolError {
206
251
  && typeof (value as Record<string, unknown>).code === 'string'
207
252
  && typeof (value as Record<string, unknown>).message === 'string'
208
253
  }
254
+
255
+ function isWireFailure(value: unknown): value is RemoteWireFailure {
256
+ return typeof value === 'object' && value !== null
257
+ && typeof (value as Record<string, unknown>).code === 'string'
258
+ && typeof (value as Record<string, unknown>).message === 'string'
259
+ }
package/src/server.ts CHANGED
@@ -1,20 +1,20 @@
1
1
  /**
2
- * Bridge WebSocket carrier: token-authenticated connection registry, gateway
3
- * RPC passthrough, per-connection event pump, and tool-call dispatch to the
2
+ * Bridge WebSocket carrier: token-authenticated connection registry, Typert
3
+ * Remote passthrough (unary + streams), and tool-call dispatch to the
4
4
  * connected browser extension.
5
5
  *
6
6
  * The route this server mounts (`/ext/bridge`) lives OUTSIDE the /api trust
7
7
  * fence (which only guards the client-connection routes), so the bridge brings
8
8
  * its own authentication: a bearer token presented in the `hello` frame within
9
- * HELLO_TIMEOUT_MS. Gateway RPCs are dispatched through the same fetch-shaped
10
- * handler the /api carrier uses (`toFetchHandler`), so schema validation and
11
- * error envelopes are identical to the GUI path. Methods the /api carrier
12
- * pins to loopback (`PRIVILEGED_METHODS`) stay loopback-only here regardless
13
- * of the token, defense in depth for `--host 0.0.0.0` deployments.
9
+ * HELLO_TIMEOUT_MS. RPC and stream frames speak the alpha Typert dialect
10
+ * verbatim: slash-joined endpoints, native `args` objects, and unmodified
11
+ * follow frames. Methods the bridge pins to loopback (`PRIVILEGED_METHODS`)
12
+ * stay loopback-only here regardless of the token, defense in depth for
13
+ * `--host 0.0.0.0` deployments.
14
14
  *
15
15
  * One active connection at a time: a new authenticated socket replaces the
16
- * previous one (the old socket is closed and its in-flight tool calls settle
17
- * as `bridge-closed`).
16
+ * previous one (the old socket is closed, its in-flight tool calls settle as
17
+ * `bridge-closed`, and its streams are aborted).
18
18
  *
19
19
  * @module
20
20
  */
@@ -23,7 +23,6 @@ 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 type { MuxFrame, RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api'
27
26
  import {
28
27
  HELLO_TIMEOUT_MS,
29
28
  PING_INTERVAL_MS,
@@ -31,33 +30,37 @@ import {
31
30
  type BridgeFrame,
32
31
  type BridgeCaps,
33
32
  type ClientFrame,
33
+ type RemoteWireResult,
34
34
  type ToolErrorCode,
35
35
  } from './protocol.ts'
36
36
  import { verifyToken } from './token.ts'
37
37
 
38
38
  /**
39
- * Gateway methods the /api carrier pins to loopback (mirror of
40
- * client-connection's PRIVILEGED_METHODS; kept verbatim so the two fences
41
- * cannot drift). The bridge rejects these for non-loopback remotes even with
42
- * a valid token.
39
+ * Gateway endpoints the bridge pins to loopback (the rc line's
40
+ * PRIVILEGED_METHODS, restated against the alpha Remote endpoint names:
41
+ * settings/credentials mutation and host-desktop/filesystem actions). The
42
+ * bridge rejects these for non-loopback remotes even with a valid token.
43
43
  */
44
44
  const PRIVILEGED_METHODS = new Set([
45
- 'host.pickDirectory',
46
- 'host.openPath',
47
- 'settings.describe',
48
- 'settings.openDocument',
49
- 'settings.update',
50
- 'settings.replace',
51
- 'settings.mutate',
52
- 'credentials.describe',
53
- 'credentials.set',
54
- 'credentials.unset',
45
+ 'settings/describe',
46
+ 'settings/openSettingsDocument',
47
+ 'settings/openAgentPresetDirectory',
48
+ 'settings/update',
49
+ 'settings/replace',
50
+ 'settings/mutate',
51
+ 'credentials/describe',
52
+ 'credentials/set',
53
+ 'credentials/unset',
54
+ 'directoryPicker/pick',
55
+ 'directoryPicker/createDirectory',
56
+ 'directoryPicker/list',
57
+ 'session/openWorkspacePath',
55
58
  ])
56
59
 
57
60
  /** Session mutations whose WebSocket arrival order is behaviorally significant. */
58
61
  const ORDERED_SESSION_METHODS = new Set([
59
- 'session.prompt',
60
- 'session.cancel',
62
+ 'session/prompt',
63
+ 'session/cancel',
61
64
  ])
62
65
 
63
66
  /**
@@ -66,8 +69,9 @@ const ORDERED_SESSION_METHODS = new Set([
66
69
  */
67
70
  function orderedSessionId(frame: Extract<ClientFrame, { t: 'rpc' }>): string | undefined {
68
71
  if (!ORDERED_SESSION_METHODS.has(frame.method)) return undefined
69
- if (typeof frame.payload !== 'object' || frame.payload === null || Array.isArray(frame.payload)) return undefined
70
- const sessionId = (frame.payload as Record<string, unknown>).sessionId
72
+ const request = frame.args.request
73
+ if (typeof request !== 'object' || request === null || Array.isArray(request)) return undefined
74
+ const sessionId = (request as Record<string, unknown>).sessionId
71
75
  return typeof sessionId === 'string' ? sessionId : undefined
72
76
  }
73
77
 
@@ -91,10 +95,14 @@ export class BridgeToolError extends Error {
91
95
  export interface BridgeServerDeps {
92
96
  /** Bearer token the extension must present in `hello`. */
93
97
  token: string
94
- /** Fetch-shaped gateway carrier (from `toFetchHandler(ctx.apiProxy)`). */
95
- apiHandler: { fetch: (request: Request) => Promise<Response> }
96
- /** Per-connection event stream (usually `ctx.apiProxy.events.mux`). */
97
- openEvents: (signal: AbortSignal) => AsyncIterable<RpcRequest<MuxFrame>>
98
+ /**
99
+ * Unary Remote dispatch (slash endpoint + native args), answering the
100
+ * RemoteResult wire form. Plugin-side interceptors (workspace grouping,
101
+ * session deferral) sit on this seam.
102
+ */
103
+ dispatchRpc: (method: string, args: Record<string, unknown>, signal: AbortSignal) => Promise<RemoteWireResult>
104
+ /** Open one Remote stream (slash endpoint + native args). */
105
+ openStream: (method: string, args: Record<string, unknown>, signal: AbortSignal) => Promise<AsyncIterable<unknown>>
98
106
  /** Default per-tool-call timeout in ms. */
99
107
  toolTimeoutMs: number
100
108
  /** Capabilities to echo in `hello.ok` (negotiated snapshot budgets). */
@@ -118,14 +126,21 @@ interface PendingTool {
118
126
  timer: NodeJS.Timeout
119
127
  }
120
128
 
129
+ /** One open Remote stream owned by the current connection. */
130
+ interface OpenStream {
131
+ abort: AbortController
132
+ pump: Promise<void>
133
+ }
134
+
121
135
  /** A socket that passed authentication and owns the single active slot. */
122
136
  interface ReadyConnection {
123
137
  ws: WebSocket
124
138
  /** Remote address captured at upgrade time (loopback gate for privileged methods). */
125
139
  remoteAddress: string | undefined
126
140
  abort: AbortController
127
- pump: Promise<void>
128
141
  ping: NodeJS.Timeout
142
+ /** Streams opened by this connection, keyed by the client-minted stream id. */
143
+ streams: Map<string, OpenStream>
129
144
  }
130
145
 
131
146
  function sendFrame(ws: WebSocket, frame: BridgeFrame): void {
@@ -240,7 +255,7 @@ export class BridgeServer {
240
255
 
241
256
  /**
242
257
  * Terminate the server: close the acceptor, drop all sockets, reject all
243
- * in-flight tool calls.
258
+ * in-flight tool calls, abort all streams.
244
259
  * @returns a promise resolving after the acceptor and all pumps stop.
245
260
  */
246
261
  async close(): Promise<void> {
@@ -248,8 +263,8 @@ export class BridgeServer {
248
263
  // "The server is not running" when closing an already-closed server).
249
264
  if (this.closed) return
250
265
  this.closed = true
251
- // Capture the live pump BEFORE replaceConnection nulls the connection.
252
- const pumps = this.current === null ? [] : [this.current.pump]
266
+ // Capture the live stream pumps BEFORE replaceConnection clears the map.
267
+ const pumps = this.current === null ? [] : [...this.current.streams.values()].map((stream) => stream.pump)
253
268
  this.replaceConnection()
254
269
  for (const socket of this.wss.clients) socket.terminate()
255
270
  this.current = null
@@ -326,22 +341,7 @@ export class BridgeServer {
326
341
  this.replaceConnection()
327
342
  const abort = new AbortController()
328
343
  const ping = setInterval(() => { sendFrame(ws, { t: 'ping' }) }, this.deps.pingIntervalMs ?? PING_INTERVAL_MS)
329
- const pump = (async () => {
330
- try {
331
- for await (const envelope of this.deps.openEvents(abort.signal)) {
332
- if (ws.readyState !== WebSocket.OPEN) break
333
- sendFrame(ws, {
334
- t: 'event',
335
- frame: { rpcId: envelope.rpcId, method: envelope.payload.type, payload: envelope.payload },
336
- })
337
- }
338
- } catch (error: unknown) {
339
- if (!abort.signal.aborted && ws.readyState === WebSocket.OPEN) {
340
- sendFrame(ws, { t: 'error', code: 'stream-failed', message: String(error) })
341
- }
342
- }
343
- })()
344
- this.current = { ws, remoteAddress, abort, pump, ping }
344
+ this.current = { ws, remoteAddress, abort, ping, streams: new Map() }
345
345
  sendFrame(ws, { t: 'hello.ok', caps: this.deps.caps })
346
346
  ws.once('close', () => {
347
347
  clearInterval(ping)
@@ -354,6 +354,12 @@ export class BridgeServer {
354
354
  case 'rpc':
355
355
  this.routeRpc(frame)
356
356
  break
357
+ case 'stream.open':
358
+ this.openStream(frame)
359
+ break
360
+ case 'stream.close':
361
+ this.closeStream(frame.id)
362
+ break
357
363
  case 'tool.result':
358
364
  this.settleTool(frame.id, frame.ok, frame.ok ? frame.result : frame.error)
359
365
  break
@@ -361,7 +367,8 @@ export class BridgeServer {
361
367
  case 'hello':
362
368
  case 'hello.ok':
363
369
  case 'rpc.result':
364
- case 'event':
370
+ case 'stream.frame':
371
+ case 'stream.error':
365
372
  case 'tool.call':
366
373
  case 'ping':
367
374
  case 'error':
@@ -394,41 +401,79 @@ export class BridgeServer {
394
401
  void task.then(clear, clear)
395
402
  }
396
403
 
404
+ /** Whether the connection owning this frame may call the endpoint at all. */
405
+ private forbidden(method: string): boolean {
406
+ const conn = this.current
407
+ return conn !== null && PRIVILEGED_METHODS.has(method) && !isLoopbackAddress(conn.remoteAddress)
408
+ }
409
+
397
410
  private async handleRpc(frame: Extract<ClientFrame, { t: 'rpc' }>): Promise<void> {
398
411
  const conn = this.current
399
412
  /* v8 ignore next -- replacement race: a frame can land between a socket
400
413
  replacement and the next promotion; the re-check keeps the handler total */
401
414
  if (conn === null) return
402
- const forbidden = PRIVILEGED_METHODS.has(frame.method) && !isLoopbackAddress(conn.remoteAddress)
403
- if (forbidden) {
415
+ if (this.forbidden(frame.method)) {
404
416
  sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: false, error: { code: 'forbidden', message: 'method is loopback-only' } })
405
417
  return
406
418
  }
407
- const body = JSON.stringify({ type: 'client-request', rpcId: frame.id, method: frame.method, payload: frame.payload })
408
- const request = new Request(new URL(`/api/${frame.method}`, 'http://dsh.internal'), {
409
- method: 'POST',
410
- headers: { 'content-type': 'application/json' },
411
- body,
412
- })
413
419
  try {
414
- const response = await this.deps.apiHandler.fetch(request)
415
- const text = await response.text()
416
- if (!response.ok) {
417
- sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: false, error: { code: 'http', message: text } })
418
- return
420
+ const result = await this.deps.dispatchRpc(frame.method, frame.args, conn.abort.signal)
421
+ if (result.ok) {
422
+ sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: true, value: result.value })
423
+ } else {
424
+ sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: false, error: result.error })
419
425
  }
420
- let result: unknown
421
- try {
422
- result = JSON.parse(text)
423
- } catch {
424
- result = text
425
- }
426
- sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: true, result })
427
426
  } catch (error: unknown) {
428
427
  sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: false, error: { code: 'internal', message: String(error) } })
429
428
  }
430
429
  }
431
430
 
431
+ /** Open one Remote stream and pump its frames until closed, failed, or replaced. */
432
+ private openStream(frame: Extract<ClientFrame, { t: 'stream.open' }>): void {
433
+ const conn = this.current
434
+ if (conn === null) return
435
+ if (this.forbidden(frame.method)) {
436
+ sendFrame(conn.ws, { t: 'stream.error', id: frame.id, message: 'method is loopback-only' })
437
+ return
438
+ }
439
+ // A repeated stream id replaces the old subscription (protocol violation,
440
+ // but closing beats leaking).
441
+ this.closeStream(frame.id)
442
+ const ws = conn.ws
443
+ const abort = new AbortController()
444
+ conn.abort.signal.addEventListener('abort', () => { abort.abort() }, { once: true })
445
+ let pump!: Promise<void>
446
+ pump = (async () => {
447
+ try {
448
+ const iterable = await this.deps.openStream(frame.method, frame.args, abort.signal)
449
+ for await (const value of iterable) {
450
+ if (ws.readyState !== WebSocket.OPEN) break
451
+ sendFrame(ws, { t: 'stream.frame', id: frame.id, frame: value })
452
+ }
453
+ } catch (error: unknown) {
454
+ if (!abort.signal.aborted && ws.readyState === WebSocket.OPEN) {
455
+ sendFrame(ws, { t: 'stream.error', id: frame.id, message: String(error) })
456
+ }
457
+ } finally {
458
+ const current = this.current
459
+ if (current !== null && current.streams.get(frame.id)?.pump === pump) {
460
+ current.streams.delete(frame.id)
461
+ }
462
+ }
463
+ })()
464
+ conn.streams.set(frame.id, { abort, pump })
465
+ }
466
+
467
+ /** Abort one open stream (client `stream.close`). */
468
+ private closeStream(id: string): void {
469
+ const conn = this.current
470
+ if (conn === null) return
471
+ const stream = conn.streams.get(id)
472
+ if (stream === undefined) return
473
+ conn.streams.delete(id)
474
+ stream.abort.abort()
475
+ }
476
+
432
477
  private settleTool(id: string, ok: boolean, payload: unknown): void {
433
478
  const pending = this.pendingTools.get(id)
434
479
  if (pending === undefined) return
@@ -438,13 +483,15 @@ export class BridgeServer {
438
483
  else pending.reject(new BridgeToolError(payloadCode(payload), payloadMessage(payload)))
439
484
  }
440
485
 
441
- /** Close the current connection (if any) and settle its in-flight calls. */
486
+ /** Close the current connection (if any) and settle its in-flight calls and streams. */
442
487
  private replaceConnection(): void {
443
488
  const conn = this.current
444
489
  if (conn === null) return
445
490
  this.current = null
446
491
  clearInterval(conn.ping)
447
492
  conn.abort.abort()
493
+ for (const stream of conn.streams.values()) stream.abort.abort()
494
+ conn.streams.clear()
448
495
  if (conn.ws.readyState === WebSocket.OPEN || conn.ws.readyState === WebSocket.CONNECTING) {
449
496
  conn.ws.close(4000, 'replaced')
450
497
  }