@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.
@@ -20,9 +20,17 @@
20
20
  * @module dsh-remote-bridge/core/envelope
21
21
  */
22
22
 
23
+ import { deflateRawSync } from 'node:zlib'
24
+
23
25
  /** Largest single text frame either direction may carry, in UTF-8 bytes: 10 MiB. */
24
26
  export const MAX_FRAME_BYTES = 10 * 1024 * 1024
25
27
 
28
+ /**
29
+ * Smallest frame the host compresses, in UTF-8 bytes. Below it the DEFLATE
30
+ * header alone can outweigh a small object, so such a frame is never even tried.
31
+ */
32
+ export const FRAME_DEFLATE_MIN_BYTES = 1024
33
+
26
34
  /** Reserved response id for a frame whose own id could not be recovered. */
27
35
  export const UNIDENTIFIED_FRAME_ID = 0
28
36
 
@@ -141,6 +149,44 @@ export function encodeFrame(frame: ServerFrame): string {
141
149
  return JSON.stringify(frame)
142
150
  }
143
151
 
152
+ /**
153
+ * How one encoded frame crosses the wire: as the text the codec produced, or as
154
+ * raw DEFLATE of exactly that text.
155
+ */
156
+ export type OutboundPayload =
157
+ | { readonly binary: false; readonly text: string }
158
+ | { readonly binary: true; readonly deflated: Buffer }
159
+
160
+ /**
161
+ * Decide the wire form of one encoded frame.
162
+ *
163
+ * The decision is a byte-level question only, asked after the frame has been
164
+ * measured against {@link MAX_FRAME_BYTES}: the text is deflated exactly as it
165
+ * stands, so a peer that inflates gets back the frame the text path would have
166
+ * written. A frame below {@link FRAME_DEFLATE_MIN_BYTES}, and a frame DEFLATE
167
+ * does not shrink (zlib's default level), both stay text — a binary frame that
168
+ * is larger than the text it replaces would pay for itself in neither direction.
169
+ * @param text - the frame as {@link encodeFrame} produced it.
170
+ * @param compress - whether the peer declared the capability that permits this.
171
+ * @param deflate - the compressor: zlib's raw DEFLATE at its default level, unless
172
+ * a caller injects one. Real deflate shrinks every frame that reaches the
173
+ * threshold, so an injected compressor is the only way to exercise the no-gain
174
+ * rule with content that truly cannot be compressed.
175
+ * @returns the text, or raw DEFLATE of it.
176
+ */
177
+ export function outboundPayloadOf(
178
+ text: string,
179
+ compress: boolean,
180
+ deflate: (source: Buffer) => Buffer = deflateRawSync,
181
+ ): OutboundPayload {
182
+ if (!compress) return { binary: false, text }
183
+ const source = Buffer.from(text, 'utf8')
184
+ if (source.length < FRAME_DEFLATE_MIN_BYTES) return { binary: false, text }
185
+ const deflated = deflate(source)
186
+ if (deflated.length >= source.length) return { binary: false, text }
187
+ return { binary: true, deflated }
188
+ }
189
+
144
190
  /** One successful response frame. */
145
191
  export function responseFrame(id: number, result: unknown): ResFrame {
146
192
  return { t: 'res', id, ok: true, r: result }
@@ -0,0 +1,197 @@
1
+ /**
2
+ * The bridge's extension seam: the one place another plugin adds methods and
3
+ * events to protocol v1 without the bridge learning what they mean.
4
+ *
5
+ * The bridge publishes this seam as the cordis service
6
+ * {@link REMOTE_BRIDGE_SERVICE}. A plugin registers a table of methods plus the
7
+ * capability a client must declare before those methods exist for it, and
8
+ * publishes events to the clients that declared the capability it names.
9
+ * Nothing here carries protocol vocabulary of its own: method names, payloads,
10
+ * topics and refusal codes belong to the registering plugin, which is why this
11
+ * module never appears in `KNOWN_METHODS` and never reads a payload.
12
+ *
13
+ * A connection dispatches an extension method only after the protocol's own
14
+ * gates: an unregistered name, a plugin that is not mounted, and a client that
15
+ * never declared the capability all answer `unknown-method` — the method is
16
+ * absent from that client's protocol, not refused by it.
17
+ * @module dsh-remote-bridge/core/extension
18
+ */
19
+
20
+ import type { RemoteBridgeDeltas } from './delta.ts'
21
+ import { KNOWN_METHODS } from './protocol.ts'
22
+
23
+ /** Cordis service this seam is published under. */
24
+ export const REMOTE_BRIDGE_SERVICE = 'remoteBridge'
25
+
26
+ /**
27
+ * Who is calling one extension method.
28
+ *
29
+ * The bridge exposes no device or session identity here on purpose: what an
30
+ * extension keys by connection is its own decision.
31
+ */
32
+ export interface RemoteBridgeCall {
33
+ /**
34
+ * Stable identity of the calling connection, unique within this bridge
35
+ * process. Two calls from one socket carry the same id; a reconnected socket
36
+ * carries a new one, because nothing proves it is the same peer.
37
+ */
38
+ readonly connectionId: string
39
+ /**
40
+ * @param capability - one capability name of this protocol or of the calling
41
+ * extension.
42
+ * @returns whether this connection announced it in `hello`.
43
+ *
44
+ * The seam hands handlers the same predicate the bridge itself gates on, so
45
+ * an extension can gate behind a bridge capability (§15's `delta.v1`) without
46
+ * holding a copy of the client's declaration.
47
+ */
48
+ declares(capability: string): boolean
49
+ /**
50
+ * This connection's delta windows, released with the connection.
51
+ *
52
+ * The mechanism of §15 lives once, in this bridge, and an extension borrows it
53
+ * per connection: the difference is always computed where the last answer is
54
+ * already held, and a dropped connection takes its base with it instead of
55
+ * leaving one to be expired by a second registry.
56
+ */
57
+ readonly deltas: RemoteBridgeDeltas
58
+ }
59
+
60
+ /**
61
+ * What one extension method answers: the response body, or a refusal stated in
62
+ * the extension's own code vocabulary. The bridge forwards either verbatim —
63
+ * it holds no table of extension codes and invents none.
64
+ */
65
+ export type RemoteBridgeMethodResult =
66
+ | { readonly ok: true; readonly r?: unknown }
67
+ | { readonly ok: false; readonly code: string; readonly msg: string }
68
+
69
+ /** One client-callable method an extension owns. */
70
+ export type RemoteBridgeMethodHandler = (
71
+ payload: Readonly<Record<string, unknown>>,
72
+ call: RemoteBridgeCall,
73
+ ) => RemoteBridgeMethodResult | Promise<RemoteBridgeMethodResult>
74
+
75
+ /** A table of methods and the capability that admits a client to them. */
76
+ export interface RemoteBridgeMethods {
77
+ /**
78
+ * Capability a client declares in `hello`'s `cap` array before these methods
79
+ * are part of its protocol. Absent means every paired connection may call
80
+ * them; an unpaired connection never may, whatever it declared.
81
+ */
82
+ readonly capability?: string
83
+ /** Method name to handler; the name is the extension's, not the bridge's. */
84
+ readonly methods: Readonly<Record<string, RemoteBridgeMethodHandler>>
85
+ }
86
+
87
+ /** The seam, exactly as published on {@link REMOTE_BRIDGE_SERVICE}. */
88
+ export interface RemoteBridgeFace {
89
+ /**
90
+ * Add methods to the protocol surface.
91
+ * @returns the disposer withdrawing them; afterwards they answer `unknown-method` again.
92
+ */
93
+ registerMethods(table: RemoteBridgeMethods): () => void
94
+ /**
95
+ * Publish one event to the connections that are paired — and, when a
96
+ * capability is named, have declared it.
97
+ * @returns how many connections took the frame.
98
+ */
99
+ broadcast(topic: string, payload: unknown, capability?: string): number
100
+ }
101
+
102
+ /** The fan-out the seam publishes through; `BridgeHub` satisfies it. */
103
+ export interface RemoteBridgeFanout {
104
+ broadcast(topic: string, payload: unknown): number
105
+ broadcastTo(capability: string, topic: string, payload: unknown): number
106
+ }
107
+
108
+ /** One registered method. */
109
+ interface RegisteredMethod {
110
+ readonly capability: string | undefined
111
+ readonly handler: RemoteBridgeMethodHandler
112
+ }
113
+
114
+ /**
115
+ * The methods extensions registered, and the capability each one needs.
116
+ *
117
+ * Every connection consults this registry; nothing else holds extension state,
118
+ * so unmounting one plugin withdraws exactly its own methods.
119
+ */
120
+ export class RemoteBridgeRegistry {
121
+ readonly #methods = new Map<string, RegisteredMethod>()
122
+
123
+ /**
124
+ * Register one table of methods, all or nothing: a table naming a protocol
125
+ * method, an empty name or a name already taken is refused before any of its
126
+ * methods becomes callable.
127
+ * @param table - the methods and the capability they require.
128
+ * @returns the disposer withdrawing this table; idempotent.
129
+ */
130
+ registerMethods(table: RemoteBridgeMethods): () => void {
131
+ const entries: [string, RegisteredMethod][] = []
132
+ for (const [name, handler] of Object.entries(table.methods)) {
133
+ if (name.trim() === '') throw new Error('a remote bridge method needs a non-empty name')
134
+ if (typeof handler !== 'function') throw new Error(`remote bridge method ${name} has no handler`)
135
+ // A protocol method is decided by the bridge's own dispatch. Shadowing one
136
+ // here would change protocol v1 without changing its version, so it is
137
+ // refused at registration rather than resolved by dispatch order.
138
+ if (KNOWN_METHODS.has(name)) throw new Error(`remote bridge method ${name} is a protocol method`)
139
+ if (this.#methods.has(name)) throw new Error(`remote bridge method ${name} is already registered`)
140
+ entries.push([name, { capability: table.capability, handler }])
141
+ }
142
+ for (const [name, entry] of entries) this.#methods.set(name, entry)
143
+ return () => {
144
+ for (const [name, entry] of entries) {
145
+ // Identity, not just the name: a table registered after this disposer
146
+ // ran keeps its own method.
147
+ if (this.#methods.get(name) === entry) this.#methods.delete(name)
148
+ }
149
+ }
150
+ }
151
+
152
+ /**
153
+ * @param method - the method name a client asked for.
154
+ * @returns whether any plugin registered it, whatever capability it requires.
155
+ */
156
+ has(method: string): boolean {
157
+ return this.#methods.has(method)
158
+ }
159
+
160
+ /**
161
+ * @param method - the method name a client asked for.
162
+ * @param declares - whether the calling connection declared a capability.
163
+ * @returns the handler when the caller may use the method, else undefined.
164
+ */
165
+ handlerFor(method: string, declares: (capability: string) => boolean): RemoteBridgeMethodHandler | undefined {
166
+ const entry = this.#methods.get(method)
167
+ if (entry === undefined) return undefined
168
+ if (entry.capability !== undefined && !declares(entry.capability)) return undefined
169
+ return entry.handler
170
+ }
171
+ }
172
+
173
+ /**
174
+ * Compose the published seam over a registry and a fan-out.
175
+ * @param methods - the registry this bridge owns.
176
+ * @param fanout - the hub's broadcast pair.
177
+ * @returns the face a plugin resolves from {@link REMOTE_BRIDGE_SERVICE}.
178
+ */
179
+ export function createRemoteBridgeFace(methods: RemoteBridgeRegistry, fanout: RemoteBridgeFanout): RemoteBridgeFace {
180
+ return {
181
+ registerMethods: table => methods.registerMethods(table),
182
+ broadcast: (topic, payload, capability) => capability === undefined
183
+ ? fanout.broadcast(topic, payload)
184
+ : fanout.broadcastTo(capability, topic, payload),
185
+ }
186
+ }
187
+
188
+ declare module '@deepseek-ai/cordis' {
189
+ interface Context {
190
+ /**
191
+ * The bridge's extension seam, while this package serves protocol v1. A
192
+ * plugin resolves it structurally at use time: requiring it would let the
193
+ * bridge's absence take the registering plugin's start down with it.
194
+ */
195
+ remoteBridge: RemoteBridgeFace
196
+ }
197
+ }
package/src/core/hub.ts CHANGED
@@ -18,9 +18,10 @@
18
18
  */
19
19
 
20
20
  import type { ApprovalOutcome } from '@deepseek-ai/dsh-user-approval'
21
+ import type { PendingPromptView } from './approvals.ts'
21
22
  import type { BridgeConnectionOptions, BridgeTransport, ConnectionAuth } from './connection.ts'
22
23
  import { BridgeConnection } from './connection.ts'
23
- import { CAP_QUESTIONS, TOPIC_APPROVAL_REQUEST, TOPIC_QUESTION_REQUEST } from './protocol.ts'
24
+ import { CAP_APPROVALS, CAP_QUESTIONS, TOPIC_APPROVAL_REQUEST, TOPIC_QUESTION_REQUEST } from './protocol.ts'
24
25
  import type { ClaimedQuestionView, QuestionAnswer, QuestionRequestPayload, QuestionState, UserQuestionRequestLike } from './questions.ts'
25
26
 
26
27
  /**
@@ -41,17 +42,45 @@ export function approvalSummary(request: ApprovalRequestLike): string {
41
42
  return request.displayReason?.zh ?? request.displayReason?.en ?? request.toolName
42
43
  }
43
44
 
45
+ /** The `approval.request` payload one claim is published with. */
46
+ export interface ApprovalRequestPayload {
47
+ readonly sessionId: string
48
+ readonly id: string
49
+ readonly summary: string
50
+ readonly toolName: string
51
+ }
52
+
53
+ /**
54
+ * The `approval.request` payload for one claim.
55
+ *
56
+ * The first broadcast and the replay of a still-open claim go through this one
57
+ * function, so the card a phone was originally shown and the same card handed to
58
+ * it again after a reconnect cannot drift apart.
59
+ * @param prompt - the claim being published.
60
+ */
61
+ function approvalPayload(prompt: PendingPromptView): ApprovalRequestPayload {
62
+ return { sessionId: prompt.sessionId, id: prompt.id, summary: prompt.summary, toolName: prompt.toolName }
63
+ }
64
+
44
65
  /**
45
66
  * The `question.request` payload for one claim.
46
67
  *
47
- * No `expiresAt`: the host's foreground deadline is not part of the request the
48
- * waterfall carries, and a bridge-invented deadline would be a timeout of the
49
- * bridge's own — the exact thing this channel must not have.
68
+ * `expiresAt` appears only once the claim learned the host's own deadline from
69
+ * its wait subscription, and it is the host's deadline unchanged: the bridge
70
+ * invents none, because a bridge-invented deadline would be a timeout of the
71
+ * bridge's own — the exact thing this channel must not have. A blocking ask
72
+ * therefore publishes no such key at all, rather than an empty or null one.
50
73
  * @param state - whether the foreground ask still holds the question.
51
74
  * @param question - the claim being published.
52
75
  */
53
76
  function questionPayload(state: QuestionState, question: ClaimedQuestionView): QuestionRequestPayload {
54
- return { sessionId: question.sessionId, callId: question.callId, state, questions: question.questions }
77
+ return {
78
+ sessionId: question.sessionId,
79
+ callId: question.callId,
80
+ state,
81
+ questions: question.questions,
82
+ ...(question.expiresAt === undefined ? {} : { expiresAt: question.expiresAt }),
83
+ }
55
84
  }
56
85
 
57
86
  /** The bridge's live connections plus the answerer it composes onto the approval chain. */
@@ -78,9 +107,16 @@ export class BridgeHub {
78
107
  attach(transport: BridgeTransport, auth?: ConnectionAuth): BridgeConnection {
79
108
  // The replay hook is wired here rather than by the caller: a phone that
80
109
  // reconnects mid-question was not there for the broadcast, and every
81
- // construction path has to hand it the live claims.
110
+ // construction path has to hand it the live claims — the approval ones and
111
+ // the user-question ones alike.
82
112
  const connection = new BridgeConnection(
83
- { ...this.#options, onDeclare: (fresh) => { this.replayQuestions(fresh) } },
113
+ {
114
+ ...this.#options,
115
+ onDeclare: (fresh) => {
116
+ this.replayQuestions(fresh)
117
+ this.replayApprovals(fresh)
118
+ },
119
+ },
84
120
  transport,
85
121
  auth,
86
122
  )
@@ -120,10 +156,6 @@ export class BridgeHub {
120
156
  return delivered
121
157
  }
122
158
 
123
- /**
124
- * Publish one event to every paired device that announced a capability.
125
- * @returns how many connections actually took the frame.
126
- */
127
159
  /**
128
160
  * Hand one freshly declared connection the questions it can now answer.
129
161
  *
@@ -138,6 +170,33 @@ export class BridgeHub {
138
170
  }
139
171
  }
140
172
 
173
+ /**
174
+ * Hand one freshly declared connection the approvals it can now answer.
175
+ *
176
+ * The same shape as {@link replayQuestions} and for the same reason: the first
177
+ * `approval.request` of a question was broadcast to the phones that were
178
+ * connected at that instant, so a phone that reconnected — or a session screen
179
+ * opened after the fact — holds no card and has no other way to learn the
180
+ * question exists. Only unsettled questions are in the registry, so one that
181
+ * was answered, one the bridge timed out and one withdrawn with the last phone
182
+ * cannot be replayed.
183
+ *
184
+ * The replay emits a frame and nothing else: the claim keeps the deadline it
185
+ * was opened with, so re-handing a question never lengthens how long the agent
186
+ * waits for it.
187
+ * @param connection - the connection that just declared its capabilities.
188
+ */
189
+ replayApprovals(connection: BridgeConnection): void {
190
+ if (!connection.paired || !connection.declares(CAP_APPROVALS)) return
191
+ for (const prompt of this.#options.approvals.openPrompts()) {
192
+ connection.emit(TOPIC_APPROVAL_REQUEST, approvalPayload(prompt))
193
+ }
194
+ }
195
+
196
+ /**
197
+ * Publish one event to every paired device that announced a capability.
198
+ * @returns how many connections actually took the frame.
199
+ */
141
200
  broadcastTo(capability: string, topic: string, payload: unknown): number {
142
201
  let delivered = 0
143
202
  for (const connection of this.#connections) {
@@ -162,12 +221,7 @@ export class BridgeHub {
162
221
  summary: approvalSummary(request),
163
222
  ...(request.signal === undefined ? {} : { signal: request.signal }),
164
223
  })
165
- const delivered = this.broadcast(TOPIC_APPROVAL_REQUEST, {
166
- sessionId,
167
- id: prompt.id,
168
- summary: prompt.summary,
169
- toolName: request.toolName,
170
- })
224
+ const delivered = this.broadcast(TOPIC_APPROVAL_REQUEST, approvalPayload(prompt))
171
225
  // A question nobody could receive is withdrawn immediately instead of
172
226
  // waiting out the phone's timeout with the agent blocked on it.
173
227
  if (delivered === 0) this.#options.approvals.abandon([prompt.id])
@@ -184,7 +238,9 @@ export class BridgeHub {
184
238
  * when the ask is timed, and minted here when it is blocking and the host
185
239
  * assigned none — either way the phone answers the id it was shown. A claim
186
240
  * nobody received is withdrawn at once instead of holding the agent until the
187
- * host's deadline.
241
+ * host's deadline. For a timed ask the host's own remaining wait travels with
242
+ * the first frame as `expiresAt`, and every later move of that deadline is
243
+ * re-published under the same call id.
188
244
  * @param request - the pending question batch.
189
245
  * @param next - the rest of the answerer chain.
190
246
  * @returns the phone's answer, the host's own deadline outcome, or whatever the next answerer says.
@@ -215,9 +271,25 @@ export class BridgeHub {
215
271
  // phone is told which state it is in instead of losing the question.
216
272
  this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload('continued', question))
217
273
  },
274
+ onDeadline: (question): void => {
275
+ // The host moved its deadline. Re-publishing the open state under the same
276
+ // call id updates the card the phone already holds instead of opening a
277
+ // second one.
278
+ this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload('open', question))
279
+ },
218
280
  })
219
281
  if (claim === undefined) return await next()
220
- const delivered = this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload('open', claim))
282
+ // The host's own first wait frame is folded into this same frame: a phone is
283
+ // handed the question and how long it has together, rather than a card that a
284
+ // second update then races. A claim with no frame publishes no deadline,
285
+ // which is exactly the payload from before this channel existed.
286
+ const expiresAt = await claim.deadline
287
+ // The host's own lifetime can end while the first wait frame is still being
288
+ // awaited — its signal aborts, so the claim is expired or already continued.
289
+ // Publishing now would hand the phone a card nobody can retract, so that case
290
+ // goes straight to the claim's own outcome: the host's reason, or its answer.
291
+ if (this.#options.questions.stateOf(callId) !== 'open') return await claim.answer
292
+ const delivered = this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload('open', expiresAt === undefined ? claim : { ...claim, expiresAt }))
221
293
  // A client that cannot receive this is not going to receive it later: the claim
222
294
  // must not be left holding the host's ask with no card anywhere. A client that
223
295
  // *can* receive it but was reconnecting is a different case — it is handed the