@linxin666/dsh-remote-bridge 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.
@@ -27,6 +27,15 @@ export const CLOSE_PROTOCOL_ERROR = 1002
27
27
  export const CLOSE_UNSUPPORTED_DATA = 1003
28
28
  /** Close code for a message past the size this bridge will carry. */
29
29
  export const CLOSE_TOO_LARGE = 1009
30
+ /**
31
+ * Close code for a peer that stopped answering: a liveness ping went out and no
32
+ * frame at all came back before its deadline.
33
+ *
34
+ * It is an application-range code (4000-4999), so a client can tell a peer that
35
+ * went silent from a protocol fault, from a frame this bridge will not carry,
36
+ * and from the ordinary 1001 teardown of a bridge that is unloading.
37
+ */
38
+ export const CLOSE_LIVENESS_TIMEOUT = 4000
30
39
 
31
40
  /** @returns the `Sec-WebSocket-Accept` value for a client's key. */
32
41
  export function webSocketAccept(secWebSocketKey: string): string {
@@ -115,6 +124,11 @@ export function encodeTextFrame(text: string): Buffer {
115
124
  return encodeServerFrame(OPCODE_TEXT, Buffer.from(text, 'utf8'))
116
125
  }
117
126
 
127
+ /** Encode one binary message: already-encoded payload bytes, never a text frame. */
128
+ export function encodeBinaryFrame(payload: Buffer): Buffer {
129
+ return encodeServerFrame(OPCODE_BINARY, payload)
130
+ }
131
+
118
132
  /** Encode one close frame with a code and a short reason. */
119
133
  export function encodeCloseFrame(code: number, reason: string): Buffer {
120
134
  const text = Buffer.from(reason, 'utf8').subarray(0, 123)
@@ -12,7 +12,7 @@
12
12
  import type { IncomingMessage } from 'node:http'
13
13
  import type { Duplex } from 'node:stream'
14
14
  import type { BridgeTransport, ConnectionAuth } from '../core/connection.ts'
15
- import { MAX_FRAME_BYTES } from '../core/envelope.ts'
15
+ import { MAX_FRAME_BYTES, outboundPayloadOf } from '../core/envelope.ts'
16
16
  import type { BridgeHub } from '../core/hub.ts'
17
17
  import {
18
18
  CLOSE_PROTOCOL_ERROR,
@@ -24,6 +24,7 @@ import {
24
24
  OPCODE_PING,
25
25
  OPCODE_PONG,
26
26
  OPCODE_TEXT,
27
+ encodeBinaryFrame,
27
28
  encodeCloseFrame,
28
29
  encodeServerFrame,
29
30
  encodeTextFrame,
@@ -105,6 +106,25 @@ export function refuseUpgrade(socket: Duplex, status: number, reason: string): v
105
106
  socket.end(`HTTP/1.1 ${status} ${reason}\r\nconnection: close\r\ncontent-length: 0\r\n\r\n`)
106
107
  }
107
108
 
109
+ /** The Nagle switch a `net.Socket` carries; the bare duplexes of a suite need not have one. */
110
+ interface DelayableSocket extends Duplex {
111
+ setNoDelay?: (noDelay: boolean) => void
112
+ }
113
+
114
+ /**
115
+ * Ask the kernel to write each frame out as it is handed over.
116
+ *
117
+ * Every frame on this route is already one whole application message, and a
118
+ * phone pays a round trip for each answer, so Nagle's coalescing window only
119
+ * delays bytes that nothing else is waiting to join. It is set on acceptance
120
+ * because that is the last moment the socket is still ours alone: once the
121
+ * upgrade has been answered, a peer's frame can already be on the way.
122
+ */
123
+ function stopNagleDelay(socket: Duplex): void {
124
+ const delayable: DelayableSocket = socket
125
+ if (typeof delayable.setNoDelay === 'function') delayable.setNoDelay(true)
126
+ }
127
+
108
128
  /**
109
129
  * One accepted upgrade handed to the bridge.
110
130
  */
@@ -134,6 +154,7 @@ export interface UpgradeHandoff {
134
154
  */
135
155
  export function serveUpgrade(handoff: UpgradeHandoff): WebSocketCarrier {
136
156
  const { socket, secWebSocketKey, head, hub, auth } = handoff
157
+ stopNagleDelay(socket)
137
158
  const carrier = new WebSocketCarrier(socket)
138
159
  carrier.handshake(secWebSocketKey)
139
160
  const connection = hub.attach(carrier, auth)
@@ -162,6 +183,8 @@ export class WebSocketCarrier implements BridgeTransport {
162
183
  #closed = false
163
184
  #onMessage: ((text: string) => void) | undefined
164
185
  #onClose: (() => void) | undefined
186
+ /** Whether the peer declared it can inflate a compressed frame; see {@link frameDeflate}. */
187
+ #deflate = false
165
188
  /** Messages that arrived before a handler was registered; see {@link deliver}. */
166
189
  readonly #pending: string[] = []
167
190
 
@@ -219,10 +242,21 @@ export class WebSocketCarrier implements BridgeTransport {
219
242
  }
220
243
  }
221
244
 
222
- /** Send one text frame. */
245
+ /**
246
+ * Record the peer's `frame.deflate.v1` declaration, as `hello` reported it.
247
+ *
248
+ * It defaults to off, so a connection that never declares the capability keeps
249
+ * the text frame this carrier always wrote, byte for byte.
250
+ */
251
+ frameDeflate(declared: boolean): void {
252
+ this.#deflate = declared
253
+ }
254
+
255
+ /** Send one frame: the text itself, or raw DEFLATE of it as a binary frame. */
223
256
  send(text: string): void {
224
257
  if (this.#closed) return
225
- this.#socket.write(encodeTextFrame(text))
258
+ const payload = outboundPayloadOf(text, this.#deflate)
259
+ this.#socket.write(payload.binary ? encodeBinaryFrame(payload.deflated) : encodeTextFrame(payload.text))
226
260
  }
227
261
 
228
262
  /** Send a close frame and end the socket. Idempotent. */
package/src/index.ts CHANGED
@@ -38,6 +38,8 @@ import type {} from '@deepseek-ai/dsh-user-approval'
38
38
  import { ApprovalRegistry } from './core/approvals.ts'
39
39
  import type { ConnectionAuth } from './core/connection.ts'
40
40
  import { DeviceRoster } from './core/devices.ts'
41
+ import { createRemoteBridgeFace, RemoteBridgeRegistry, REMOTE_BRIDGE_SERVICE } from './core/extension.ts'
42
+ import { JobRoster, type JobRegistryFace } from './core/jobs.ts'
41
43
  import { BridgeHub } from './core/hub.ts'
42
44
  import { createOwnerPeer } from './core/owner-peer.ts'
43
45
  import { PairingService } from './core/pairing.ts'
@@ -46,6 +48,7 @@ import { WS_PATH } from './core/protocol.ts'
46
48
  import { SessionMeta, type ArchiveSetFace, type SessionStoreFace, type SessionTitleFace } from './core/session-meta.ts'
47
49
  import { SessionPermissions, type ApprovalPolicyFace, type PermissionPresetsFace, type SandboxPolicyFace } from './core/session-permissions.ts'
48
50
  import { dshHome } from './host/dsh-home.ts'
51
+ import { mountOnce } from './mount-once.ts'
49
52
  import { makePairTokenRoute } from './host/routes.ts'
50
53
  import { isWebSocketUpgrade, presentedTokenOf, readSecWebSocketKey, refuseUpgrade, serveUpgrade } from './host/websocket.ts'
51
54
 
@@ -150,11 +153,35 @@ function permissionFaces(ctx: Context) {
150
153
  }
151
154
  }
152
155
 
156
+ /**
157
+ * Resolve the host's job registry, now.
158
+ *
159
+ * Read per call, never captured at mount, for the reason the metadata faces
160
+ * are: `jobs` is not in this plugin's `inject` list, so a host that composes
161
+ * no job plugin still serves protocol v1 — `jobs.list` answers
162
+ * `jobs-unavailable` instead of the bridge failing to start. The face is
163
+ * structural: this package imports no part of the registry's own types.
164
+ * @param ctx - the plugin's context.
165
+ * @returns the job faces as they stand right now.
166
+ */
167
+ function jobFaces(ctx: Context) {
168
+ return {
169
+ jobs: ctx.get('jobs') as JobRegistryFace | undefined,
170
+ }
171
+ }
172
+
153
173
  /**
154
174
  * Mount the bridge.
175
+ *
176
+ * Guarded by the family's single-instance rule: the aggregate row
177
+ * (`web-ui-remote-bridge`) and a standalone install of this same package can
178
+ * both be live in one profile, and the second mount would otherwise register
179
+ * `/ios/v1` and the token route a second time. Whichever source mounts first
180
+ * owns the package name; the other is queued and replayed when that owner
181
+ * disposes.
155
182
  * @param ctx - the plugin's context, carrying the gateway and web server.
156
183
  */
157
- export function apply(ctx: Context): void {
184
+ function applyImpl(ctx: Context): void {
158
185
  const log = (message: string): void => { console.log(`[remote-bridge] ${message}`) }
159
186
  const roster = new DeviceRoster({ file: join(dshHome(), ROSTER_PATH), log })
160
187
  const pairing = new PairingService()
@@ -164,14 +191,23 @@ export function apply(ctx: Context): void {
164
191
  // it is gated by the bridge's own pairing check (see core/owner-peer.ts).
165
192
  const ownerPeer = createOwnerPeer(ctx)
166
193
  const questions = new QuestionClaims({ gateway: ctx.typertGateway, peer: ownerPeer, log })
194
+ // One roster per mount, shared by every connection: a background job is a fact
195
+ // about the host, not about the device that asked about it.
196
+ const jobs = new JobRoster({ faces: () => jobFaces(ctx), log })
167
197
  const sessionMeta = new SessionMeta(() => sessionMetaFaces(ctx), () => Date.now(), log)
168
198
  const permissions = new SessionPermissions(() => permissionFaces(ctx), log)
199
+ // The extension seam publishes no protocol vocabulary of its own: another
200
+ // plugin registers the method names, payloads and topics it owns, and this
201
+ // package only dispatches and fans out what it was handed.
202
+ const extensions = new RemoteBridgeRegistry()
169
203
  const hub = new BridgeHub({
204
+ extensions,
170
205
  gateway: ctx.typertGateway,
171
206
  pairing,
172
207
  roster,
173
208
  approvals,
174
209
  questions,
210
+ jobs,
175
211
  sessionMeta,
176
212
  permissions,
177
213
  ownerPeer,
@@ -180,6 +216,13 @@ export function apply(ctx: Context): void {
180
216
  log,
181
217
  })
182
218
 
219
+ // A capture-only test context implements no service registry; a Host always
220
+ // does. Without it the bridge still serves protocol v1, minus other plugins'
221
+ // methods, which is exactly what not publishing the seam means.
222
+ if (typeof (ctx as { provide?: unknown }).provide === 'function') {
223
+ ctx.provide(REMOTE_BRIDGE_SERVICE, createRemoteBridgeFace(extensions, hub))
224
+ }
225
+
183
226
  ctx.effect(() => {
184
227
  void roster.load()
185
228
  const disposeUpgrade = ctx.webServer.registerUpgrade({
@@ -192,6 +235,7 @@ export function apply(ctx: Context): void {
192
235
  disposeUpgrade()
193
236
  disposeRoute()
194
237
  hub.dispose()
238
+ jobs.dispose()
195
239
  }
196
240
  }, 'remote-bridge: protocol v1 routes')
197
241
 
@@ -203,3 +247,11 @@ export function apply(ctx: Context): void {
203
247
  // first answer settles it.
204
248
  ctx.on('user-questions/request', (request, next) => hub.question(request, next), { prepend: true })
205
249
  }
250
+
251
+ /**
252
+ * The plugin's mount point: {@link applyImpl} behind the family's
253
+ * single-instance guard. The name is the npm package identity, which every
254
+ * install source of this plugin shares — the aggregate's `web-ui-remote-bridge`
255
+ * row and the standalone `remote-bridge` row alike.
256
+ */
257
+ export const apply = mountOnce('@linxin666/dsh-remote-bridge', applyImpl)
@@ -0,0 +1,142 @@
1
+ // Generated by scripts/sync-shared.mjs from shared/host/mount-once.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
2
+ /**
3
+ * Host single-instance guard shared by the plugin family. The family bundle
4
+ * (dsh-web-all / dsh-skins) namespaces every child row id (web-ui-*), so
5
+ * the loader accepts a standalone install of the same package side by side;
6
+ * without this guard the second instance would still re-register the same
7
+ * webserver routes, tools, settings namespaces, and system-prompt sections
8
+ * and fail the boot. mountOnce makes a mount of an already-mounted package a
9
+ * no-op for as long as the first instance lives (the browser half is already
10
+ * deduped by package name in the client module host).
11
+ *
12
+ * A no-op is only safe while the holder is ALIVE. The holder can be disposed
13
+ * long after the refused mount ran its course: the Host reloads a profile by
14
+ * creating the new loader entries before the old ones are torn down (a
15
+ * plugin-manager enable/disable/install write, a settings-driven row reload,
16
+ * HMR), so the new aggregate shell entry mounts its family plugin while the
17
+ * previous entry still owns the name. Dropping that refused mount lost the
18
+ * plugin for good - the previous entry then disposed its own mount, releasing
19
+ * the name with nobody left to take it, and the family row stayed listed as
20
+ * active while its host routes 404ed (the task-board panel showed
21
+ * "board.hostError.notMounted", no degraded record appeared, and only a Host
22
+ * restart recovered it).
23
+ *
24
+ * The refused mount is therefore QUEUED, not dropped, and replayed the moment
25
+ * the holder releases the name - if the waiting fiber is still alive then. The
26
+ * single-instance guarantee is unchanged: exactly one mount is live per
27
+ * package name, and the replay re-enters the guard so a later mount still
28
+ * dedupes against it.
29
+ *
30
+ * The registry rides a global symbol so two module instances of the same
31
+ * package (npm copy vs repository link) still share one verdict. That symbol
32
+ * is a CROSS-REPOSITORY contract, not this file's private state: the four
33
+ * satellite packages (dsh-skins / dsh-pet / dsh-presets /
34
+ * dsh-community-plugins) are separate repositories carrying their own copy of
35
+ * this guard, rebuilt on their own schedule, so the value under `MOUNTED`
36
+ * must keep the shape every published copy reads (a `Set` of package names
37
+ * with `has`/`add`/`delete`). The wait queues this guard added therefore live
38
+ * under their own additive key, and the registry reads back a `Set` even when
39
+ * some other build left a different value there. Changing `MOUNTED`'s shape
40
+ * in place broke that contract once: a satellite's legacy copy created a
41
+ * `Set`, the family's new copy read it as a `Map`, and every family row
42
+ * mounted after it failed with "claims.get is not a function".
43
+ *
44
+ * cordis `ctx.effect` runs its callback immediately and treats the callback's
45
+ * return value as the fiber disposer, so the unmarker is returned, not run.
46
+ */
47
+
48
+ /** Published cross-repository contract: package names currently mounted. */
49
+ const MOUNTED = Symbol.for('dsh-web.mounted-plugins')
50
+
51
+ /** Additive key this guard owns: refused mounts waiting for the name. */
52
+ const WAITERS = Symbol.for('dsh-web.mounted-plugins.waiters')
53
+
54
+ /** The slice of a cordis context this guard touches. */
55
+ interface MountContext {
56
+ effect?: (effect: () => unknown) => unknown
57
+ }
58
+
59
+ /** One mount that was refused while another fiber owned the package name. */
60
+ interface PendingMount {
61
+ /** Replay the refused mount; a no-op once its own fiber has been disposed. */
62
+ run(): void
63
+ }
64
+
65
+ interface MountRegistry {
66
+ [MOUNTED]?: unknown
67
+ [WAITERS]?: Map<string, PendingMount[]>
68
+ }
69
+
70
+ /**
71
+ * The shared name registry, always a `Set` whatever another build stored here:
72
+ * a foreign value (an interim shape, a hand-written global) must not take every
73
+ * family plugin down with it.
74
+ * @returns the process-wide set of mounted package names.
75
+ */
76
+ function mountedSet(): Set<string> {
77
+ const registry = globalThis as MountRegistry
78
+ const existing = registry[MOUNTED]
79
+ if (existing instanceof Set) return existing as Set<string>
80
+ const created = new Set<string>()
81
+ registry[MOUNTED] = created
82
+ return created
83
+ }
84
+
85
+ /** Queue per package name for mounts refused while a holder was alive. */
86
+ function mountWaiters(): Map<string, PendingMount[]> {
87
+ const registry = globalThis as MountRegistry
88
+ return (registry[WAITERS] ??= new Map())
89
+ }
90
+
91
+ /**
92
+ * Wrap a cordis plugin apply so the package runs at most once per process.
93
+ * The first mount registers normally and releases the name when its fiber
94
+ * disposes; a mount refused while that name is held waits for the release and
95
+ * then runs, unless its own fiber disposes first.
96
+ * @param packageName - npm package identity shared by every install source.
97
+ * @param fn - the original plugin apply.
98
+ * @returns an apply of the same shape.
99
+ */
100
+ export function mountOnce<T extends (...args: any[]) => unknown>(packageName: string, fn: T): T {
101
+ const mount = (...args: unknown[]): unknown => {
102
+ const mounted = mountedSet()
103
+ const ctx = args[0] as MountContext | undefined
104
+ if (mounted.has(packageName)) {
105
+ // Another fiber (the aggregate row, a standalone install, or a copy built
106
+ // from an older revision of this guard) owns the name. Queue instead of
107
+ // dropping: dropping lost the plugin for the rest of the process when the
108
+ // holder was disposed by a reload.
109
+ const waiters = mountWaiters()
110
+ const queue = waiters.get(packageName) ?? []
111
+ let alive = true
112
+ const pending: PendingMount = {
113
+ run: () => {
114
+ if (alive) mount(...args)
115
+ },
116
+ }
117
+ // A fiber that dies while it waits must not be replayed afterwards: its
118
+ // context is disposed and registering effects on it would throw.
119
+ ctx?.effect?.(() => () => {
120
+ alive = false
121
+ const index = queue.indexOf(pending)
122
+ if (index >= 0) queue.splice(index, 1)
123
+ })
124
+ queue.push(pending)
125
+ waiters.set(packageName, queue)
126
+ return
127
+ }
128
+ mounted.add(packageName)
129
+ ctx?.effect?.(() => () => {
130
+ mounted.delete(packageName)
131
+ const waiters = mountWaiters()
132
+ const queue = waiters.get(packageName)
133
+ if (queue === undefined) return
134
+ waiters.delete(packageName)
135
+ // Defer the handover one microtask so the disposing mount's own effects
136
+ // (routes, ledger, timers) are torn down before the next one registers.
137
+ for (const waiter of queue.splice(0)) queueMicrotask(() => { waiter.run() })
138
+ })
139
+ return fn(...args)
140
+ }
141
+ return mount as T
142
+ }